package com.sxfq.loansupermarket.backsystem.modular.arrival.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.core.util.AliyunOssUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersArriveInfo;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.SearchMembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Medium;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.PointRewordInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerDetailsService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerPublicService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IGetListService;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.logsf.entity.TreatmentUnitlLogInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.StoreRecordsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.system.service.IDeptService;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.BindingInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.DepartmentInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import com.sxfq.loansupermarket.backsystem.modular.websocket.WebSocket;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.MemberEnumConfig;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.MedicalAdviceInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.IWxService;
import io.swagger.models.auth.In;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author py
 * @Date 2019年4月19日23:15:54
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {
    @Autowired
    ICustomerService service;

    @Autowired
    ICustomerPublicService customerPublicService;

    @Autowired
    IConsultantService consultantService;

    @Autowired
    IGetListService getListService;

    @Autowired
    private MemberProductService memberProductService;

    @Autowired
    AliyunOssUtil aliyunOssUtil;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    ICustomerDetailsService customerDetailsService;

    @Autowired
    IDeptService deptService;

    @Autowired
    WebSocket webSocket;

    @Autowired
    private IWxService wxService;

    private String PREFIX = "/arrival/customer/";

    private String PREFIY = "/tcCenter/consultant/";

    /**
     * 跳转到到店客户管理页面
     */
    @RequestMapping("")
    public String customer(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("sttleAccountsTime", ShiroKit.getUser().getSttleAccountsTime());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        model.addAttribute("deptid", ShiroKit.getUser().getDeptId());
        return PREFIX + "customer.html";
    }


    /**
     * 跳转到到店短信群发
     */
    @RequestMapping("customerTwo")
    public String customerTwo(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("sttleAccountsTime", ShiroKit.getUser().getSttleAccountsTime());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        model.addAttribute("deptid", ShiroKit.getUser().getDeptId());
        return PREFIX + "customer_two.html";
    }

    /**
     * 跳转到到店客户管理页面
     */
    @RequestMapping(value = "/to_sendMedicalAdvice/{customerPhone}")
    public String to_sendMedicalAdvice(@PathVariable String customerPhone, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getSessionAttr("medicalAdviceUnitList") == null) {
            String sql = "select id,medical_advice_unit from medical_advice_info;";
            List<MedicalAdviceInfo> medicalAdviceInfoList = sqlMapper.selectList(sql, MedicalAdviceInfo.class);
            ShiroKit.setSessionAttr("medicalAdviceUnitList", medicalAdviceInfoList);
        }
        model.addAttribute("customerPhone", customerPhone);
        model.addAttribute("medicalAdviceUnitList", ShiroKit.getSessionAttr("medicalAdviceUnitList"));
        return PREFIX + "medical_advice.html";
    }

    /**
     * 修改是否响铃提示预约视图变动状态
     */
    @RequestMapping(value = "/updateIsRing")
    @ResponseBody
    public int updateIsRing(@RequestParam("id") int id, @RequestParam("status") String status) throws Exception {
        String sql = "update user set register_is_ring='" + status + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 跳转修改信息
     */
    @RequestMapping("/customer_modificationSum")
    public String customer_modificationSum(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        return PREFIX + "customer_modificationSum.html";
    }

    /**
     * 跳转市场预约
     */
    @RequestMapping("/customer_marketBooking")
    public String customer_marketBooking(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIX + "customer_marketBooking.html";
    }

    /**
     * 未匹配到患者添加页面
     */
    @RequestMapping(value = "/to_nature_courtyard_add/{customerPhone}")
    public String to_nature_courtyard_add(@PathVariable String customerPhone, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getCharactersList() == null) {
            String getListSql = "select id, characters from character_info order by num asc;";
            List<CharacterInfo> charactersList=sqlMapper.selectList(getListSql,CharacterInfo.class);
            ShiroKit.getUser().setCharactersList(charactersList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("consumAbilityList") == null) {
            String getListSql = "select id, consum_ability from consum_ability_info order by  num asc;";
            List<ConsumAbilityInfo> consumAbilityList = sqlMapper.selectList(getListSql, ConsumAbilityInfo.class);
            ShiroKit.setSessionAttr("consumAbilityList", consumAbilityList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getConsumptionHabitsList() == null) {
            String getListSql = "select id, consumption_habits from consumption_habits_info order by  num asc;";
            List<ConsumptionHabitsInfo> consumptionHabitsList = sqlMapper.selectList(getListSql, ConsumptionHabitsInfo.class);
            ShiroKit.getUser().setConsumptionHabitsList(consumptionHabitsList);
        }
        model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
        model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("customerPhone", customerPhone);
        model.addAttribute("province", ShiroKit.getUser().getProvince());
        model.addAttribute("cities", ShiroKit.getUser().getCities());
        return PREFIX + "customer_receptionOne.html";
    }

    /**
     * 修改患者信息
     */
    @RequestMapping(value = "/updateCustomerInfoOk/{reservationsId}")
    @ResponseBody
    public String updateCustomerInfoOk(@PathVariable String reservationsId, @Valid CustomerInfo info, Model model) {
        if (StringUtil.isEmpty(info.getCustomerAge())) {
            info.setCustomerAge(0);
        }
        String rt = "";
        String sql1 = "update reservations_info set customer_name='" + info.getCustomerName() + "'," +
                "customer_age='" + info.getCustomerAge() + "',one_channel='" + info.getOneChannel() + "'," +
                "one_medium='" + info.getOneMedium() + "',province='" + info.getProvince() + "'," +
                "customer_phone='" + info.getCustomerPhone() + "',customer_sex='" + info.getCustomerSex() + "'," +
                "two_channel='" + info.getTwoChannel() + "',two_medium='" + info.getTwoMedium() + "'," +
                "cities='" + info.getCities() + //"',phone_shar_ship='" + info.getPhoneSharShip() +
                "', thr_channel='" + info.getThrChannel() + "'," +
                "thr_medium='" + info.getThrMedium() + "',region='" + info.getRegion() + "' " +
                " where id='" + reservationsId + "'  ";
        rt = "" + sqlMapper.update(sql1) + "," + reservationsId;
        String sql2 = "select id from " + ShiroKit.getUser().getCustomer_info() + " where arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null and reservations_id='" + reservationsId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql2, CustomerInfo.class);
        if (customerInfo != null) {
            if (info.getBirthday() == "" || "".equals(info.getBirthday())) {
                info.setBirthday("null");
            }
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_name='" + info.getCustomerName() + "'," +
                    "customer_age='" + info.getCustomerAge() + "',one_channel='" + info.getOneChannel() + "'," +
                    "one_medium='" + info.getOneMedium() + "',province='" + info.getProvince() + "'," +
                    "customer_phone='" + info.getCustomerPhone() + "',customer_sex='" + info.getCustomerSex() + "'," +
                    "two_channel='" + info.getTwoChannel() + "',two_medium='" + info.getTwoMedium() + "'," +
                    "cities='" + info.getCities() + //"',phone_shar_ship='" + info.getPhoneSharShip() +
                    "',customer_status='" + info.getCustomerStatus() + "'," +
                    "birthday= " + info.getBirthday() + " ,thr_channel='" + info.getThrChannel() + "'," +
                    "thr_medium='" + info.getThrMedium() + "',region='" + info.getRegion() + "' " +
                    " where reservations_id='" + reservationsId + "'  ";
            rt = sqlMapper.update(sql) + "," + reservationsId;
        }
        return rt;
    }

    /**
     * 跳转到初到点亮页面
     */
    @RequestMapping(value = "/customer_add/{id}")
    public String customerAdds(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        ReservationsInfo reservationsInfo = reservationsService.selectOneById2(id);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("consumAbilityList") == null) {
            String getListSql = "select id, consum_ability from consum_ability_info order by  num asc;";
            List<ConsumAbilityInfo> consumAbilityList = sqlMapper.selectList(getListSql, ConsumAbilityInfo.class);
            ShiroKit.setSessionAttr("consumAbilityList", consumAbilityList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getEconomicAbilityList() == null) {
            String getListSql = "select id, economic_ability from economic_ability_info order by num asc;";
            List<EconomicAbilityInfo> economicAbilityList = sqlMapper.selectList(getListSql, EconomicAbilityInfo.class);
            ShiroKit.getUser().setEconomicAbilityList(economicAbilityList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getCharactersList() == null) {
            String getListSql = "select id, characters from character_info order by num asc;";
            List<CharacterInfo> charactersList=sqlMapper.selectList(getListSql,CharacterInfo.class);
            ShiroKit.getUser().setCharactersList(charactersList);
        }
        if (ShiroKit.getUser().getConsumptionHabitsList() == null) {
            String getListSql = "select id, consumption_habits from consumption_habits_info order by  num asc;";
            List<ConsumptionHabitsInfo> consumptionHabitsList = sqlMapper.selectList(getListSql, ConsumptionHabitsInfo.class);
            ShiroKit.getUser().setConsumptionHabitsList(consumptionHabitsList);
        }
        model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
        model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsId", reservationsInfo.getId());
        model.addAttribute("customerPhone", reservationsInfo.getCustomerPhone());
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("customerStatus", "新客首次");
        model.addAttribute("province", ShiroKit.getUser().getProvince());
        model.addAttribute("cities", ShiroKit.getUser().getCities());
        return PREFIX + "customer_receptionTwo.html";
    }

    //作废到店患者
    @RequestMapping(value = "/openToVoid/{customerId}")
    public String openToVoid(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("customerId", customerId);
        return PREFIX + "to_void.html";
    }

    /**
     * 选择TC
     */
    @RequestMapping(value = "/to_choiceTc/{id}")
    public String choiceTc(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("customerId", id);
        return PREFIY + "customer_choiceTc.html";
    }

    @RequestMapping(value = "/orthodontics_choiceTc/{id}")
    public String orthodontics_choiceTc(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("id", id);
        return PREFIY + "orthodontics_choiceTc.html";
    }


    @RequestMapping(value = "/earnest_choiceTc/{id}")
    public String earnest_choiceTc(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("id", id);
        return PREFIY + "earnest_choiceTc.html";
    }

    /**
     * 跳转到会员查询界面
     */
    @RequestMapping("/customer_member")
    public String customerMember(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "customer_member.html";
    }

    /**
     * 选择医生
     */
    @RequestMapping(value = "/to_updateDoctor/{id}")
    public String to_updateDoctor(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        model.addAttribute("customerId", id);
        return PREFIY + "customer_updateDoctor.html";
    }

    //修改医生
    @RequestMapping(value = "/choiceDoctor", method = RequestMethod.POST)
    @ResponseBody
    public int choiceDoctor(String customerId, String doctor, String remarks) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String rek = "";
        if (StringUtil.isNotEmpty(remarks)) {
            rek = "；" + remarks + "";
        }
        String sq1 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.doctor='" + doctor + "',remarks=concat(remarks,'" + rek + "') where id='" + customerId + "'";
        return sqlMapper.update(sq1);
    }

    /**
     * 选择客户状态
     */
    @RequestMapping(value = "/to_choice_status/{id}")
    public String toChoiceStatus(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("customerId", id);
        return PREFIY + "customer_choice_customerstatus.html";
    }

    /**
     * 储值交易
     */
    @RequestMapping(value = "/depositTransaction/{customerId}")
    public String depositTransaction(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select id,customer_name as customerName,money_balance as moneyBalance,reservations_id as reservationsId ,field_tc as fieldTc from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("checkoutMethodList") == null) {
            String selectsqlCM = "select id,checkout_method as checkoutMethod from checkout_method_info where charge_bill_is_inCash=1 order by num ;";
            ShiroKit.setSessionAttr("checkoutMethodList", sqlMapper.selectList(selectsqlCM));
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("checkoutMethodList", ShiroKit.getSessionAttr("checkoutMethodList"));
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIY + "customer_depositTransaction.html";
    }

    /**
     * 储值录入
     */
    @RequestMapping(value = "/addCustomerErnest", method = RequestMethod.POST)
    @ResponseBody
    public int addCustomerErnest(String remarks, String customerId, String[] str, String mode, String reservationsId, String fieldTcValue, Model model) {
        return service.addCustomerErnest(remarks, customerId, str, mode, reservationsId, fieldTcValue, model);
    }

    /**
     * 种植牙俱乐部交易
     */
    @RequestMapping(value = "/orthodonticsTransaction/{customerId}")
    public String orthodonticsTransaction(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select id,customer_name as customerName,money_balance as moneyBalance,reservations_id as reservationsId ,field_tc as fieldTc from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("checkoutMethodList") == null) {
            String selectsqlCM = "select id,checkout_method as checkoutMethod from checkout_method_info where charge_bill_is_inCash=1 order by num ;";
            ShiroKit.setSessionAttr("checkoutMethodList", sqlMapper.selectList(selectsqlCM));
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_orthodontics_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("checkoutMethodList", ShiroKit.getSessionAttr("checkoutMethodList"));
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIY + "customer_orthodonticsTransaction.html";
    }

    /**
     * 种植牙俱乐部充值
     */
    @RequestMapping(value = "/addOrthodonticsDeal", method = RequestMethod.POST)
    @ResponseBody
    public int addOrthodonticsDeal(String remarks, String customerId, String[] str, String mode, String fieldTcValue, Model model) {
        return service.addOrthodonticsDeal(remarks, customerId, str, mode, fieldTcValue, model);
    }

    /**
     * 修改时间跳转界面
     */
    @RequestMapping(value = "/update_belonger/{id}")
    public String update_belonger(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select id,reservations_id,scarchiving from " + ShiroKit.getUser().getCustomer_info() + " where id='" + id + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "update_belonger.html";
    }

    /**
     * 储值交易记录
     */
    @RequestMapping(value = "/transactionRecord/{customerId}")
    public String transactionRecord(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Double moneyBalance = 0.00;
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIY + "customer_transactionRecord.html";
    }

    /**
     * 储值交易记录
     */
    @RequestMapping(value = "/getEarnestList/{reservationsId}")
    @ResponseBody
    public List<RechargeInfo> getEarnestList(@PathVariable String reservationsId, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select t1.id,t2.customer_name as customerName,t2.customer_phone as customerPhone,t1.actual_account_balance as actualAccountBalance," +
                " t1.remarks as remarks,t1.recharge_people as rechargePeople,t1.recharge_time as rechargeTime,t1.checkout_method as checkoutMethod," +
                " t1.tc_name as tcName,t1.add_store as addStore,t1.mode as mode," +
                " (select customer_name from reservations_info where id=t1.reservations_idz limit 0,1) as customerNameZZ," +
                " (select customer_name from reservations_info where id=t1.reservations_ids limit 0,1) as customerNameSF  " +
                " from reserveMoney_deal t1 left join " + ShiroKit.getUser().getCustomer_info() + " t2 on (t1.reservations_id=t2.reservations_id)  " +
                " where t1.reservations_id='" + reservationsId + "' group by t1.id order by t1.recharge_time desc ";
        List<RechargeInfo> rechargeInfo = sqlMapper.selectList(sql, RechargeInfo.class);
        return rechargeInfo;
    }


    /**
     * 正畸俱乐部交易记录
     */
    @RequestMapping(value = "/orthodonticsTransactionRecord/{customerId}")
    public String orthodonticsTransactionRecord(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Double moneyBalance = 0.00;
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIY + "customer_orthodonticsRecord.html";
    }

    /**
     * 正畸俱乐部交易记录
     */
    @RequestMapping(value = "/getOrthodonticsList/{reservationsId}")
    @ResponseBody
    public List<RechargeInfo> getOrthodonticsList(@PathVariable String reservationsId, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select t1.id,t2.customer_name as customerName,t2.customer_phone as customerPhone,t1.actual_account_balance as actualAccountBalance," +
                " t1.remarks as remarks,t1.recharge_people as rechargePeople,t1.recharge_time as rechargeTime,t1.checkout_method as checkoutMethod," +
                " t1.tc_name as tcName,t1.add_store as addStore,t1.mode as mode,t1.end_time as endTime " +
                " from reservemoney_orthodontics_deal t1 left join " + ShiroKit.getUser().getCustomer_info() + " t2 on (t1.reservations_id=t2.reservations_id)  " +
                " where t1.reservations_id='" + reservationsId + "' group by t1.id order by t1.recharge_time desc ";
        List<RechargeInfo> rechargeInfo = sqlMapper.selectList(sql, RechargeInfo.class);
        return rechargeInfo;
    }

    //打印正畸俱乐部交易记录
    @RequestMapping(value = "/orthodonticsMoney_Print/{id}")
    public String orthodonticsMoney_Print(@PathVariable String id, Model model) {
        String sql = "select t1.id,t2.customer_name as customerName,t2.customer_phone as customerPhone,t1.actual_account_balance as actualAccountBalance," +
                " t1.remarks as remarks,t1.recharge_people as rechargePeople,t1.recharge_time as rechargeTime,t1.end_time as endTime," +
                " t1.checkout_method as checkoutMethod,t1.tc_name as tcName,t1.add_store as addStore,t2.medical_record_number as medicalRecordNumber," +
                " ( " +
                " CASE t2.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                " t2.customer_age as customerAge,t1.mode as mode " +
                " from reservemoney_orthodontics_deal t1 " +
                " left join " + ShiroKit.getUser().getCustomer_info() + " t2 on (t1.reservations_id=t2.reservations_id)  " +
                " where t1.id='" + id + "' group by t1.id limit 1";
        RechargeInfo rechargeInfo = sqlMapper.selectOne(sql, RechargeInfo.class);
        if (rechargeInfo.getCustomerNameSF() != null && rechargeInfo.getCustomerNameSF() != "") {
            rechargeInfo.setCustomerNameZZ(rechargeInfo.getCustomerName());
        } else if (rechargeInfo.getCustomerNameZZ() != null && rechargeInfo.getCustomerNameZZ() != "") {
            rechargeInfo.setCustomerNameSF(rechargeInfo.getCustomerName());
        }
        model.addAttribute("rechargeInfo", rechargeInfo);
        return PREFIX + "orthodonticsMoney_Print.html";
    }

    //打印储值交易记录
    @RequestMapping(value = "/reserveMoney_Print/{id}")
    public String reserveMoney_Print(@PathVariable String id, Model model) {
        String sql = "select t1.id,t2.customer_name as customerName,t2.customer_phone as customerPhone,t1.actual_account_balance as actualAccountBalance," +
                " t1.remarks as remarks,t1.recharge_people as rechargePeople,t1.recharge_time as rechargeTime,t1.checkout_method as checkoutMethod," +
                " t1.tc_name as tcName,t1.add_store as addStore,t2.medical_record_number as medicalRecordNumber," +
                " ( " +
                " CASE t2.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                " t2.customer_age as customerAge,t1.mode as mode," +
                " (select customer_name from reservations_info where id=t1.reservations_idz limit 0,1) as customerNameZZ," +
                " (select customer_name from reservations_info where id=t1.reservations_ids limit 0,1) as customerNameSF  " +
                " from reserveMoney_deal t1 left join " + ShiroKit.getUser().getCustomer_info() + " t2 on (t1.reservations_id=t2.reservations_id)  " +
                " where t1.id='" + id + "' group by t1.id limit 1";
        RechargeInfo rechargeInfo = sqlMapper.selectOne(sql, RechargeInfo.class);
        if (rechargeInfo.getCustomerNameSF() != null && rechargeInfo.getCustomerNameSF() != "") {
            rechargeInfo.setCustomerNameZZ(rechargeInfo.getCustomerName());
        } else if (rechargeInfo.getCustomerNameZZ() != null && rechargeInfo.getCustomerNameZZ() != "") {
            rechargeInfo.setCustomerNameSF(rechargeInfo.getCustomerName());
        }
        model.addAttribute("rechargeInfo", rechargeInfo);
        return PREFIX + "reserveMoney_print.html";
    }

    /**
     * 积分调整
     */
    @RequestMapping(value = "/integralAdjustment/{customerId}")
    public String integralAdjustment(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("vipLevelInfoList") == null) {
            String getListSql = "select id, vip_level_name, integral_factor from " + ShiroKit.getUser().getVip_level_info() + " order by num asc;";
            List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(getListSql, VipLevelInfo.class);
            ShiroKit.setSessionAttr("vipLevelInfoList", vipLevelInfoList);
        }
        String jfbalancesql1 = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo1 = sqlMapper.selectOne(jfbalancesql1, ScoreDealInfo.class);
        model.addAttribute("jfbalancea", scoreDealInfo1.getScoreBalance());
        model.addAttribute("vipLevelInfoList", ShiroKit.getSessionAttr("vipLevelInfoList"));
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("proportional", Double.parseDouble(ShiroKit.getUser().getProportional()));
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIY + "customer_integralAdjustment.html";
    }

    /**
     * 返现转账
     */
    @RequestMapping(value = "/returnCashTurnTo/{customerId}")
    public String returnCashTurnTo(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("vipLevelInfoList") == null) {
            String getListSql = "select id, vip_level_name, integral_factor from " + ShiroKit.getUser().getVip_level_info() + " order by num asc;";
            List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(getListSql, VipLevelInfo.class);
            ShiroKit.setSessionAttr("vipLevelInfoList", vipLevelInfoList);
        }
        String jfbalancesql1 = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance " +
                "from return_cash_info where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo1 = sqlMapper.selectOne(jfbalancesql1, ScoreDealInfo.class);
        model.addAttribute("jfbalancea", scoreDealInfo1.getScoreBalance());
        model.addAttribute("vipLevelInfoList", ShiroKit.getSessionAttr("vipLevelInfoList"));
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("proportional", Double.parseDouble(ShiroKit.getUser().getProportional()));
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIY + "customer_returnCashTurnTo.html";
    }


    @RequestMapping(value = "/updateBelonger", method = RequestMethod.POST)
    @ResponseBody
    public int updateScore(String customerId, String upBelongerremarks, String belonger, Model model) {
        String selectsql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectsql, CustomerInfo.class);
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set scarchiving='" + belonger + "' where id='" + customerId + "'";
        sqlMapper.update(sql);
        String sql2 = "INSERT INTO `reservations_updateBelonger_info` (`update_people`, `update_time`, `update_cname`, " +
                "`update_cphone`,`belongery`,`belongerx`,archiving,`filing_time`,`remarks`) VALUES " +
                "('" + ShiroKit.getUser().getAccount() + "' , '" + DateTimeKit.now() + "', '" + customerInfo.getCustomerName()
                + "', '" + customerInfo.getCustomerPhone() + "', '" + customerInfo.getScarchiving() + "','" + belonger
                + "','" + customerInfo.getArchiving() + "', '" + customerInfo.getFilingTime() + "', '" + upBelongerremarks + "');";
        return sqlMapper.insert(sql2);
    }

    /**
     * 修改时间跳转界面
     */
    @RequestMapping(value = "/update_time/{id}")
    public String update_time(@PathVariable String id, Model model) {
        String customerId = id;
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("customerId", customerId);
        return PREFIX + "update_time.html";
    }

    /**
     * 积分录入
     */
    @RequestMapping(value = "/addCustomerScore", method = RequestMethod.POST)
    @ResponseBody
    public int updateScore(String jfbalance, String remarks, String mode, String customerId, String reservationsId, Model model) {
        String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        String tableHead = ShiroKit.getUser().getAbbreviation();
//        String tableNamer = tableHead + "recharge_info";
//        String tableNamer2 = tableHead + "recharge_info";
        String tableNamec1 = tableHead + "customer_info";
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        String id = randomNumber + DateTimeKit.now();
        BigDecimal b1 = new BigDecimal(Double.parseDouble(ShiroKit.getUser().getProportional()));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(jfbalance));
        Double jfbalances = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if ("转积分".equals(mode)) {
            String sqla1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where reservations_id='" + reservationsId + "' limit 1";
            CustomerInfo cinfo = sqlMapper.selectOne(sqla1, CustomerInfo.class);
            if (cinfo == null) {   //转入人没来过本店，去过另一家店
                String sqla2 = "select * from distinction_customer_status a where reservations_id='" + reservationsId + "' and status=1  limit 1";
                Dept infod = sqlMapper.selectOne(sqla2, Dept.class);
                String sqld1 = "select * from " + infod.getAbbreviation() + "customer_info" + " " +
                        "where reservations_id ='" + reservationsId + "' order by arrival_time desc limit 1 ";
                cinfo = sqlMapper.selectOne(sqld1, CustomerInfo.class);
                //tableNamer2 = infod.getAbbreviation() + "recharge_info";
                tableNamec1 = infod.getAbbreviation() + "customer_info";
            }
            String insert1 = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store) values" +
                    " ('" + customerInfo.getReservationsId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "'," +
                    " '-" + jfbalance + "','" + mode + "','积分转出" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(insert1);
            String insert2 = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store) values" +
                    " ('" + cinfo.getReservationsId() + "','" + cinfo.getCustomerName() + "','" + cinfo.getCustomerPhone() + "'," +
                    " '" + jfbalance + "','" + mode + "','积分转入" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(insert2);
            //插入结账表
           /* String insertdel1 = " INSERT INTO `" + tableNamer + "` (`id`, `status`, `customer_id`, `reservations_id`, " +
                    "  `recharge_people`,`checkout_method_id`, `checkout_method`, " +
                    "  `actual_account_balance`, `recharge_time`, `operation_time`,recharges_time, " +
                    "  `remarks`, `is_record`,tc_name,isEarnes,hospital_performance,section_performance) values  " +
                    " ('" + id + rand.nextInt(9999) + "',1,'" + customerId + "','" + customerInfo.getReservationsId() + "', " +
                    " '" + ShiroKit.getUser().getAccount() +
                    "',(select id from checkout_method_info where checkout_method='积分'),'积分', '-" + jfbalances + "', '"
                    + DateTimeKit.now() + "', '" + DateTimeKit.now() + "', " +
                    " if(substr('" + DateTimeKit.now() + "',12,2)>=16,date_add(left('" + DateTimeKit.now() + "',10),INTERVAL 1 day),left('" + DateTimeKit.now() + "',10)), " +
                    " '积分转出" + remarks + "','是','" + customerInfo.getFieldTc() + "',3,0,0) ";
            sqlMapper.insert(insertdel1);
            String insertdel2 = " INSERT INTO `" + tableNamer2 + "` (`id`, `status`, `customer_id`, `reservations_id`, " +
                    "  `recharge_people`,`checkout_method_id`, `checkout_method`, " +
                    "  `actual_account_balance`, `recharge_time`, `operation_time`, recharges_time, " +
                    "  `remarks`, `is_record`,tc_name,isEarnes,hospital_performance,section_performance) values  " +
                    " ('" + id + rand.nextInt(9999) + "',1,'" + customerId + "','" + cinfo.getReservationsId() + "', " +
                    " '" + ShiroKit.getUser().getAccount() +
                    "',(select id from checkout_method_info where checkout_method='积分'),'积分', '" + jfbalances + "', '"
                    + DateTimeKit.now() + "', '" + DateTimeKit.now() + "', " +
                    " if(substr('" + DateTimeKit.now() + "',12,2)>=16,date_add(left('" + DateTimeKit.now() + "',10),INTERVAL 1 day),left('" + DateTimeKit.now() + "',10)), " +
                    " '积分转入" + remarks + "','是','" + cinfo.getFieldTc() + "',3,0,0) ";
            sqlMapper.insert(insertdel2);*/
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " a set jfbalance=jfbalance-'" + jfbalance + "',update_people='" + ShiroKit.getUser().getAccount() + "'," +
                    "update_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "'";
            String sql2 = "update " + tableNamec1 + " a set jfbalance=jfbalance+'" + jfbalance + "',update_people='" + ShiroKit.getUser().getAccount() + "'," +
                    "update_time='" + DateTimeKit.now() + "' where reservations_id='" + cinfo.getReservationsId() + "'";
            sqlMapper.update(sql2);
            return sqlMapper.update(sql);
        } else {
            String sqlinsert = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store) values" +
                    " ('" + customerInfo.getReservationsId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "','" + jfbalance + "','" + mode + "','" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(sqlinsert);
           /* //插入结账表
            String sql2c = " INSERT INTO `" + tableNamer + "` (`id`, `status`, `customer_id`, `reservations_id`, " +
                    "  `recharge_people`,`checkout_method_id`, `checkout_method`, " +
                    "  `actual_account_balance`, `recharge_time`, `operation_time`,recharges_time, " +
                    "  `remarks`, `is_record`,tc_name,isEarnes,hospital_performance,section_performance) values  " +
                    " ('" + id + "',1,'" + customerId + "','" + customerInfo.getReservationsId() + "', " +
                    " '" + ShiroKit.getUser().getAccount() +
                    "',(select id from checkout_method_info where checkout_method='积分'),'积分', '" + jfbalances + "', '"
                    + DateTimeKit.now() + "', '" + DateTimeKit.now() + "'," +
                    " if(substr('" + DateTimeKit.now() + "',12,2)>=16,date_add(left('" + DateTimeKit.now() + "',10),INTERVAL 1 day),left('" + DateTimeKit.now() + "',10)), " +
                    " '积分充值" + remarks + "','是','" + customerInfo.getFieldTc() + "',3,0,0) ";
            sqlMapper.insert(sql2c);*/
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " a set jfbalance=jfbalance+'" + jfbalance + "',update_people='" + ShiroKit.getUser().getAccount() + "'," +
                    "update_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "'";
            return sqlMapper.update(sql);
        }
    }

    /**
     * 返现转账
     */
    @RequestMapping(value = "/updateReturnCashInfo", method = RequestMethod.POST)
    @ResponseBody
    public int updateReturnCashInfo(String jfbalance, String remarks, String mode, String customerId, String reservationsId, Model model) {
        String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        if ("返现转账".equals(mode)) {
            String sqla1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where reservations_id='" + reservationsId + "' limit 1";
            CustomerInfo cinfo = sqlMapper.selectOne(sqla1, CustomerInfo.class);
            if (cinfo == null) {   //转入人没来过本店，去过另一家店
                String sqla2 = "select * from distinction_customer_status a where reservations_id='" + reservationsId + "' and status=1  limit 1";
                Dept infod = sqlMapper.selectOne(sqla2, Dept.class);
                String sqld1 = "select * from " + infod.getAbbreviation() + "customer_info" + " " +
                        "where reservations_id ='" + reservationsId + "' order by arrival_time desc limit 1 ";
                cinfo = sqlMapper.selectOne(sqld1, CustomerInfo.class);
            }
            String insert1 = "insert into return_cash_info (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_time,add_store) values" +
                    " ('" + customerInfo.getReservationsId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "'," +
                    " '-" + jfbalance + "','" + mode + "','返现转出" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(insert1);
            String insert2 = "insert into return_cash_info (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_time,add_store) values" +
                    " ('" + cinfo.getReservationsId() + "','" + cinfo.getCustomerName() + "','" + cinfo.getCustomerPhone() + "'," +
                    " '" + jfbalance + "','" + mode + "','返现转入" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(insert2);
        } else {
            String insert1 = "insert into return_cash_info (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_time,add_store) values" +
                    " ('" + customerInfo.getReservationsId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "'," +
                    " '" + jfbalance + "','" + mode + "','" + remarks + "'," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
            sqlMapper.insert(insert1);
        }
        return 1;
    }


    /**
     * 积分变动记录
     */
    @RequestMapping(value = "/changeRecord/{customerId}")
    public String changeRecord(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Double jfbalance = 0.00;
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String getjFBalance = "select sum(a.score_balance) as jfbalance from score_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        CustomerInfo customerInfo2 = sqlMapper.selectOne(getjFBalance, CustomerInfo.class);
        if (customerInfo2 != null) {
            jfbalance = customerInfo2.getJfbalance();
        }
        model.addAttribute("jfbalance", jfbalance);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIY + "customer_changeRecord.html";
    }


    /**
     * 返现记录
     */
    @RequestMapping(value = "/returnCashRecord/{customerId}")
    public String returnCashRecord(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Double jfbalance = 0.00;
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String getjFBalance = "select sum(a.score_balance) as jfbalance from return_cash_info a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        CustomerInfo customerInfo2 = sqlMapper.selectOne(getjFBalance, CustomerInfo.class);
        if (customerInfo2 != null) {
            jfbalance = customerInfo2.getJfbalance();
        }
        model.addAttribute("jfbalance", jfbalance);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIY + "customer_returnCashRecord.html";
    }

    /**
     * 设置会员卡号
     */
    @RequestMapping(value = "/to_settingMemberNum/{customerId}")
    public String to_settingMemberNum(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("vipLevelInfoList") == null) {
            String getListSql = "select id, vip_level_name, integral_factor from " + ShiroKit.getUser().getVip_level_info() + " order by num asc;";
            List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(getListSql, VipLevelInfo.class);
            ShiroKit.setSessionAttr("vipLevelInfoList", vipLevelInfoList);
        }
        model.addAttribute("vipLevelInfoList", ShiroKit.getSessionAttr("vipLevelInfoList"));
        model.addAttribute("customerInfo", customerInfo.getReservationsId());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("customerInfo", customerInfo);
        return PREFIY + "settingMembershipLevel.html";
    }

    /**
     * 积分兑换
     */
    @RequestMapping(value = "/to_pointsFor/{customerId}")
    public String to_pointsFor(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String productList = "select * from point_reword_info where area='" + ShiroKit.getUser().getAreaAbbreviation() + "' order by create_time desc ";
        List<PointRewordInfo> pointRewordInfoList = sqlMapper.selectList(productList, PointRewordInfo.class); //查询所有的商品列表
        for (PointRewordInfo pointRewordInfo : pointRewordInfoList) {
            String pointSql = "select id,product_id,image_path from point_reword_iconinfo where product_id='" + pointRewordInfo.getId() + "' and mainFigure=1 ";
            PointRewordInfo info = sqlMapper.selectOne(pointSql, PointRewordInfo.class);
            if (info != null) {
                pointRewordInfo.setProductId(info.getProductId());
                pointRewordInfo.setImagePath(info.getImagePath());
            }
        }
        model.addAttribute("customerId", customerId);
        model.addAttribute("pointRewordInfoList", pointRewordInfoList);//商品信息
        return PREFIY + "to_pointsFor.html";
    }

    //兑换成功
    @RequestMapping(value = "/verificationCodeTwo", method = RequestMethod.POST)
    @ResponseBody
    public int verificationCode(String customerId, String productId) {
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo cinfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        String strSql = "insert into point_conversion_info (product_id,reservations_id,code) " +
                "values ('" + productId + "','" + cinfo.getReservationsId() + "','" + randomNumber + "');";
        String upSql = "update point_reword_info a set a.conversioned_number=conversioned_number+1," +
                "a.putaway_number=putaway_number-1 where id='" + productId + "';"; //减少商品上架的数量，减少会员的储值余额
        // 插入到积分表中
        String insertSql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,add_people,add_store) " +
                "values('" + cinfo.getReservationsId() + "','" + cinfo.getCustomerName() + "','" + cinfo.getCustomerPhone() + "'," +
                "-(select product_price from point_reword_info where id='" + productId + "'),'商品兑换'," +
                "'" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "')";
        sqlMapper.insert(insertSql);
        sqlMapper.insert(strSql);
        return sqlMapper.update(upSql);
    }

    /**
     * 积分变动记录
     */
    @RequestMapping(value = "/getScoreDealList/{reservationsId}")
    @ResponseBody
    public List<ScoreDealInfo> getScoreDealList(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id,customer_name as customerName,customer_phone as customerPhone,score_balance as scoreBalance,mode," +
                "remarks,add_people as addPeople,add_store as addStore,add_time as addTime from score_deal where reservations_id='" + reservationsId + "' order by add_time desc";
        List<ScoreDealInfo> scoreDealInfo = sqlMapper.selectList(sql, ScoreDealInfo.class);
        return scoreDealInfo;
    }


    /**
     * 返现变动记录
     */
    @RequestMapping(value = "/getreturnCashRecordList/{reservationsId}")
    @ResponseBody
    public List<ScoreDealInfo> getreturnCashRecordList(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id,customer_name as customerName,customer_phone as customerPhone,score_balance as scoreBalance,mode," +
                "remarks,add_people as addPeople,add_store as addStore,add_time as addTime from return_cash_info" +
                " where reservations_id='" + reservationsId + "' order by add_time desc";
        List<ScoreDealInfo> scoreDealInfo = sqlMapper.selectList(sql, ScoreDealInfo.class);
        return scoreDealInfo;
    }


    //判断渠道是市场的还是到店的
    @RequestMapping(value = "/isMarket", method = RequestMethod.POST)
    @ResponseBody
    public int isMarket(String oneChannel) throws Exception {
        String sq1 = "select ismarket from channel where channelName='" + oneChannel + "' and pid=0 limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sq1, CustomerInfo.class);
        return customerInfo.getIsmarket();
    }

    //判断客户是否充值,冲积分,是否已结账或是已开单
    @RequestMapping(value = "/is_void", method = RequestMethod.POST)
    @ResponseBody
    public CustomerInfo isVoid(String customerId) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableNamed = tableHead + "deal_info";
        String tableNamer = tableHead + "recharge_info";
        CustomerInfo customerInfo = new CustomerInfo();
        String sq1 = "select id from " + tableNamer + " where customer_id='" + customerId + "' and (isEarnes=2 or isEarnes=3) limit 1";
        RechargeInfo rechargeInfo = sqlMapper.selectOne(sq1, RechargeInfo.class);
        if (rechargeInfo != null) {  //充过积分或储值
            customerInfo.setMoneyBalance(11.11);
        }
        String sql2 = "select id from " + tableNamed + " where customer_id='" + customerId + "' limit 1";
        RechargeInfo rechargeInfo1 = sqlMapper.selectOne(sql2, RechargeInfo.class);
        if (rechargeInfo1 != null) { //存在结账表中
            customerInfo.setDealStatus("已开单");
        }
        return customerInfo;
    }

    @RequestMapping(value = "/choiceTc", method = RequestMethod.POST)
    @ResponseBody
    public int choiceTc(String customerId, String tcName, String remarks) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String selsql = "select id,a.arrival_status,(case a.arrival_status when (1 or 9) then '预约' when 2 then '到店' when 3 then '就诊中' " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话' " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName,a.customer_name,a.customer_phone,a.customer_status," +
                "a.reservations_id from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(selsql, CustomerInfo.class);
        String rek = "";
        if (StringUtil.isNotEmpty(remarks)) {
            rek = "；" + remarks + "";
        }
        String sq1 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.field_tc='" + tcName + "',a.query_tc='" + tcName + "',remarks=concat(remarks,'" + rek + "') where id='" + customerId + "'";
        String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','修改TC','" + ShiroKit.getUser().getId() + "','" + customerInfo.getCustomerStatus() + "', '"
                + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','现场tc（归属tc）：" + customerInfo.getFieldTc() + "(" + customerInfo.getQueryTc() + ")->" + tcName + "','" + customerId + "','" + customerInfo.getReservationsId() + "');";
        sqlMapper.insert(sq11);
        return sqlMapper.update(sq1);
    }

    @RequestMapping(value = "/earnestChoiceTc", method = RequestMethod.POST)
    @ResponseBody
    public int earnestChoiceTc(String id, String tcName, String remarks) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String selsql = "select id,deal_id,actual_account_balance,tc_name from reservemoney_deal where id='" + id + "'";
        RechargeInfo rechargeInfo = sqlMapper.selectOne(selsql, RechargeInfo.class);
        String sql = "update reservemoney_deal set tc_name='" + tcName + "',remarks='" + remarks + "' where id='" + id + "'";
        String sql1 = "update " + ShiroKit.getUser().getRecharge_info() + " set tc_name='" + tcName + "' where id='" + rechargeInfo.getDealId() + "'";
        String sql2 = "update hospital_section_statistics set tc_name='" + tcName + "' where deal_id=(select deal_id from reservemoney_deal where id='" + id + "')";
        String inlogsql = "INSERT INTO earnest_choice_tc_log (y_tc, x_tc, money, operator,reservemoney_id,remarks) VALUES " +
                " ('" + rechargeInfo.getTcName() + "', '" + tcName + "', '" + rechargeInfo.getActualAccountBalance() + "','" + ShiroKit.getUser().getAccount() + "','" + id + "','" + remarks + "');";
        sqlMapper.insert(inlogsql);
        sqlMapper.update(sql);
        sqlMapper.update(sql1);
        return sqlMapper.update(sql2);
    }

    @RequestMapping(value = "/orthodonticsChoiceTc", method = RequestMethod.POST)
    @ResponseBody
    public int orthodonticsChoiceTc(String id, String tcName, String remarks) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String selsql = "select id,deal_id,actual_account_balance,tc_name from reservemoney_orthodontics_deal where id='" + id + "'";
        RechargeInfo rechargeInfo = sqlMapper.selectOne(selsql, RechargeInfo.class);
        String sql = "update reservemoney_orthodontics_deal set tc_name='" + tcName + "',remarks='" + remarks + "' where id='" + id + "'";
        String sql1 = "update " + ShiroKit.getUser().getRecharge_info() + " set tc_name='" + tcName + "' where id='" + rechargeInfo.getDealId() + "'";
        String sql2 = "update hospital_section_statistics set tc_name='" + tcName + "' where deal_id=(select deal_id from reservemoney_orthodontics_deal where id='" + id + "')";
        sqlMapper.update(sql);
        sqlMapper.update(sql1);
        return sqlMapper.update(sql2);
    }

    @RequestMapping(value = "/isComeToday", method = RequestMethod.POST)
    @ResponseBody
    public int isComeToday(String customerId) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return customerPublicService.isComeToday(customerId);
    }

    /**
     * 客户状态请选择
     *
     * @param customerId
     * @param customerStatus
     */
    @RequestMapping(value = "/choiceCustomerStatus", method = RequestMethod.POST)
    @ResponseBody
    public int choiceCustomerStatus(String customerId, String remarks, String customerStatus) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql3 = "select id as id,customer_name as customerName,customer_phone as customerPhone, " +
                " customer_status as customerStatus from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 1";
        CustomerInfo info = sqlMapper.selectOne(sql3, CustomerInfo.class);
        String sq1 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.customer_status='" + customerStatus + "' where id='" + customerId + "'";
        String sq11 = "INSERT INTO `customer_reservations_update_log` (`logtype`, `userid`, `customer_status`, `customer_name`,`customer_phone`,`single_person`, `createtime`,`succeed`, `message`,`classname`,`remarks`) VALUES " +
                " ( '修改'," + ShiroKit.getUser().getId() + ",'" + customerStatus + "', '" + info.getCustomerName() + "', '" + info.getCustomerPhone() + "', '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "'," +
                "'成功','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + " 把 " + info.getCustomerName() + " 的客户状态:" + info.getCustomerStatus() + " 修改为:" + customerStatus + "','" + remarks + "');";
        sqlMapper.insert(sq11);
        return sqlMapper.update(sq1);
    }

    @RequestMapping(value = "/choiceAppointment", method = RequestMethod.POST)
    @ResponseBody
    public int choiceAppointment(String customerId, String appointmentPayService) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sq1 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.appointment_pay_service='" + appointmentPayService + "' where id='" + customerId + "'";
        return sqlMapper.update(sq1);
    }

    /**
     * 前台匹配
     *
     * @param
     */
    @RequestMapping(value = "/to_binding/{data}")
    public String to_binding(@PathVariable String data, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String phone = data.trim();
        if (ToolUtil.isEmpty(phone)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phoneSql3 = "select " +
                "  (CASE a.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,a.* from reservations_info a " +
                " where (customer_phone like '%" + phone + "%' or customer_phone2 like '%" + phone + "%' )";
        List<ReservationsInfo> reservationsInfoList = sqlMapper.selectList(phoneSql3, ReservationsInfo.class);
        model.addAttribute("reservationsInfoList", reservationsInfoList);
        model.addAttribute("size", reservationsInfoList.size());
        model.addAttribute("customerPhone", data);
        return PREFIX + "nature_courtyard.html";
    }

    /**
     * 人工打分提交
     */
    @RequestMapping(value = "/membersBinding")
    @ResponseBody
    public String membersBinding(@RequestBody BindingInfo objs, HttpServletRequest request) {
        ShiroKit.setSessionAttr("membersFeature", objs.getFeature());
        ShiroKit.setSessionAttr("membersImageBs", objs.getImageBs());
        ShiroKit.setSessionAttr("membersQuality", objs.getQuality());
        ShiroKit.setSessionAttr("membersId", objs.getId());
        return objs.getMemberNum();
    }


    /**
     * 前台匹配
     *
     * @param
     */
    @RequestMapping(value = "/to_reservation_matching/{customerPhone}")
    public String to_reservation_matching(@PathVariable String customerPhone, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String phone = customerPhone.trim();
        if (ToolUtil.isEmpty(phone)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phoneSql3 = "select " +
                "  (CASE a.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,a.* from reservations_info a " +
                " where (customer_phone like '%" + phone + "%' or customer_phone2 like '%" + phone + "%' )";
        List<ReservationsInfo> reservationsInfoList = sqlMapper.selectList(phoneSql3, ReservationsInfo.class);
        model.addAttribute("reservationsInfoList", reservationsInfoList);
        model.addAttribute("size", reservationsInfoList.size());
        return PREFIX + "nature_courtyard.html";
    }

    /**
     * 跳转到预约客户管理详情页面
     */
    @RequestMapping(value = "/reconsulting/{customerId}")
    @ResponseBody
    public int reconsulting(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (customerPublicService.getUpdatePhoneCount(info.getCustomerPhone(), info.getId()).size() > 0) {
            return 0;
        } else {
            service.update(info);
            return 1;
        }
    }

    //提交变更科室
    @RequestMapping(value = "/commitChangeTreatmentUnit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> commitChangeTreatmentUnit(String customerId, String treatmentUnit) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sq1 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.treatment_unit='" + treatmentUnit + "' where id='"
                + customerId + "'";
        sqlMapper.update(sq1);
        resultMap.put("treatmentUnit", treatmentUnit);
        return resultMap;
    }

    /**
     * 跳转到重咨点亮页面
     */
    @RequestMapping(value = "/to_reconsulting/{id}")
    public String to_reconsulting(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql2 = "select id,reservations_id,customer_name,field_tc,query_tc,treatment_unit from " + ShiroKit.getUser().getCustomer_info() + " where arrival_status!=1" +
                " and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null and reservations_id= '" + id + "' order by arrival_time desc limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql2, CustomerInfo.class);
        if (customerInfo == null) {   //去另外一家店复诊,查到去的哪家店
            String sqld = "select id,abbreviation from distinction_customer_status where reservations_id ='" + id + "' and status=1  order by add_time desc limit 0,1 ";
            Dept cinfo = sqlMapper.selectOne(sqld, Dept.class);
            String sql3 = " select id,reservations_id,customer_name,field_tc,query_tc,treatment_unit from " + cinfo.getAbbreviation() + "customer_info t where " +
                    "reservations_id ='" + id + "' order by arrival_time desc limit 0,1 ";
            customerInfo = sqlMapper.selectOne(sql3, CustomerInfo.class);
            customerInfo.setAbbreviation(cinfo.getAbbreviation());
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "customer_receptionThr.html";
    }

    /**
     * 跳转到重咨点亮页面
     */
    @RequestMapping(value = "/to_reconsultingTc/{id}")
    public String to_reconsultingTc(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql2 = "select id,reservations_id,customer_name,field_tc,query_tc,treatment_unit from " + ShiroKit.getUser().getCustomer_info() + " where arrival_status!=1" +
                " and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null and reservations_id= '" + id + "' order by arrival_time desc limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql2, CustomerInfo.class);
        if (customerInfo == null) {   //去另外一家店复诊,查到去的哪家店
            String sqld = "select id,abbreviation from distinction_customer_status where reservations_id ='" + id + "' and status=1  order by add_time desc limit 0,1 ";
            Dept cinfo = sqlMapper.selectOne(sqld, Dept.class);
            String sql3 = " select id,reservations_id,customer_name,field_tc,query_tc,treatment_unit from " + cinfo.getAbbreviation() + "customer_info t where " +
                    "reservations_id ='" + id + "' order by arrival_time desc limit 0,1 ";
            customerInfo = sqlMapper.selectOne(sql3, CustomerInfo.class);
            customerInfo.setAbbreviation(cinfo.getAbbreviation());
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "customer_receptionThr_tc.html";
    }

    /**
     * 添加重咨
     */
    @RequestMapping(value = "/addNatureCustomerCZ", method = RequestMethod.POST)
    @ResponseBody
    public MembersArriveInfo addNatureCustomerCZ(String reservationsId, String customerName, String treatmentUnit,
                                                 String fieldTc, String remarks, Model model) throws ParseException {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id from " + ShiroKit.getUser().getCustomer_info() + " where reservations_id ='" + reservationsId + "' " +
                " and left(arrival_time,10)=left(now(),10) and treatment_unit='" + treatmentUnit + "'" +
                " and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10" +
                " and customer_status!='复诊' and arrival_time is not null and query_tc!='分诊TC' and query_tc!='待定TC' limit 1";
        CustomerInfo customerInfos = sqlMapper.selectOne(sql, CustomerInfo.class);
        MembersArriveInfo membersArriveInfos = new MembersArriveInfo();
        if (customerInfos != null) {
            membersArriveInfos.setIds("0");
            return membersArriveInfos;
        } else {
            String sqlseltc = "select id from " + ShiroKit.getUser().getCustomer_info() + " where reservations_id ='" + reservationsId + "' " +
                    " and left(arrival_time,10)=left(now(),10) and query_tc!='" + fieldTc + "'" +
                    " and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 " +
                    " and customer_status!='复诊' and arrival_time is not null and query_tc!='分诊TC' and query_tc!='待定TC' limit 1";
            CustomerInfo customerInfoseltc = sqlMapper.selectOne(sqlseltc, CustomerInfo.class);
            if (customerInfoseltc != null && !"待定TC".equals(fieldTc)) {
                membersArriveInfos.setIds("2");
            } else {
                String sql1 = " select * from " + ShiroKit.getUser().getCustomer_info() + " t where arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null " +
                        " and reservations_id ='" + reservationsId + "' order by arrival_time desc limit 0,1 ";
                CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
                if (customerInfo == null) {   //去另外一家店复诊,查到去的哪家店
                    String sqld = "select id,abbreviation from distinction_customer_status where reservations_id ='" + reservationsId + "' and status=1  order by add_time desc limit 0,1 ";
                    Dept cinfo = sqlMapper.selectOne(sqld, Dept.class);
                    String sql2 = " select * from " + cinfo.getAbbreviation() + "customer_info t where reservations_id ='" + reservationsId + "' order by arrival_time desc limit 0,1 ";
                    customerInfo = sqlMapper.selectOne(sql2, CustomerInfo.class);
                    customerInfo.setAbbreviation(cinfo.getAbbreviation());
//                    customerInfo.setMedicalRecordNumber(customerInfo.getMedicalRecordNumber());  //继承上一家的病历号
                    customerInfo.setYellowNumber(customerPublicService.getMaxYellowNumber()); 
                    String sqlin = "insert into distinction_customer_status (reservations_id,customer_name,customer_phone,arrival_store,abbreviation,deal_status,add_time,update_time,medical_record_number) " +
                            " values('" + customerInfo.getReservationsId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone()
                            + "','" + ShiroKit.getUser().getOutpatientName() + "','" + ShiroKit.getUser().getAbbreviation() + "','未成交','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + customerInfo.getMedicalRecordNumber() + "') ";
                    sqlMapper.insert(sqlin);//去另外一家店复诊，记录下
                } else {
                    if (customerInfo.getReferralerPerson() == null || customerInfo.getReferralerPerson() == "") {
                        customerInfo.setReferralerPerson("");
                    } else if (customerInfo.getReferralerPersoned() == null || customerInfo.getReferralerPersoned() == "") {
                        customerInfo.setReferralerPersoned("");
                    } else if (customerInfo.getReferralerTime() == null || customerInfo.getReferralerTime() == "") {
                        customerInfo.setReferralerTime(null);
                    } else if (customerInfo.getReferralerRemarks() == null || customerInfo.getReferralerRemarks() == "") {
                        customerInfo.setReferralerRemarks("");
                    } else {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date dt1 = df.parse(DateTimeKit.now().substring(0, 10));
                        Date dt2 = df.parse(customerInfo.getReferralerTime().substring(0, 10));
                        if (dt1.getTime() - dt2.getTime() > 30 * 24 * 60 * 60 * 1000L) {
                            customerInfo.setReferralerPerson("");
                            customerInfo.setReferralerPersoned("");
                            customerInfo.setReferralerRemarks("");
                            customerInfo.setReferralerTime(null);
                        } else {
                            customerInfo.setReferralerPerson(customerInfo.getReferralerPerson());
                            customerInfo.setReferralerPersoned(customerInfo.getReferralerPersoned());
                            customerInfo.setReferralerTime(customerInfo.getReferralerTime());
                            customerInfo.setReferralerRemarks(customerInfo.getReferralerRemarks());
                        }
                    }
                    customerInfo.setMedicalRecordNumber(customerInfo.getMedicalRecordNumber());
                    customerInfo.setYellowNumber(customerInfo.getYellowNumber());
                }
                customerInfo.setCustomerId(customerInfo.getId());
                customerInfo.setStartTime(customerPublicService.getStartTime());
                customerInfo.setEndTime(customerPublicService.getEndTime());
                customerInfo.setCustomerName(customerName);
                customerInfo.setTreatmentUnit(treatmentUnit);
                customerInfo.setFieldTc(fieldTc);
                customerInfo.setRemarks(remarks+customerInfo.getRemarks());
                customerInfo.setReservationsId(customerInfo.getReservationsId());
                customerInfo.setCustomerStatus(customerPublicService.getNewCustomerStatus(reservationsId));
                customerInfo.setId(service.getId());
                customerInfo.setDoctor("未指定医生");
                customerInfo.setMarketFilingTime(customerInfo.getMarketFilingTime());
                service.insertReturncz(customerInfo, reservationsId);
                membersArriveInfos = service.memberDistinguishInUp(reservationsId);
                membersArriveInfos.setIds("1");
            }
            return membersArriveInfos;
        }
    }

    /**
     * 跳转到新建一人多号页面
     */
    @RequestMapping(value = "/customer_multiple/{customerPhone}/{id}")
    public String customer_multiple(@PathVariable String customerPhone, @PathVariable("id") String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = " select t.id,t.archiving,t.follower,t.belonger, t.one_channel as oneChannel, " +
                " t.two_channel as twoChannel, t.thr_channel as thrChannel,t.one_medium as oneMedium," +
                " t.two_medium as twoMedium,t.thr_medium as thrMedium from reservations_info t where t.id='" + id + "' limit 1";
        ReservationsInfo info = sqlMapper.selectOne(sql, ReservationsInfo.class);
        if (info != null) {
            model.addAttribute("oneChannel", info.getOneChannel());
            model.addAttribute("twoChannel", info.getTwoChannel());
            model.addAttribute("thrChannel", info.getThrChannel());
            model.addAttribute("oneMedium", info.getOneMedium());
            model.addAttribute("twoMedium", info.getTwoMedium());
            model.addAttribute("thrMedium", info.getThrMedium());
            if ("null".equals(info.getFollower()) || "".equals(info.getFollower()) || info.getFollower() == null) {
                if ("null".equals(info.getArchiving()) || "".equals(info.getArchiving()) || info.getArchiving() == null) {
                    if ("null".equals(info.getBelonger()) || "".equals(info.getBelonger()) || info.getBelonger() == null) {
                        model.addAttribute("userName", ShiroKit.getUser().getAccount());
                    } else {
                        model.addAttribute("userName", info.getBelonger());
                    }
                } else {
                    model.addAttribute("userName", info.getArchiving());
                }
            } else {
                model.addAttribute("userName", info.getFollower());
            }
        } else {
            model.addAttribute("oneChannel", "直接上门");
            model.addAttribute("twoChannel", "请选择");
            model.addAttribute("thrChannel", "请选择");
            model.addAttribute("oneMedium", "请选择");
            model.addAttribute("twoMedium", "请选择");
            model.addAttribute("thrMedium", "请选择");
            model.addAttribute("userName", ShiroKit.getUser().getAccount());
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("consumAbilityList") == null) {
            String getListSql = "select id, consum_ability from consum_ability_info order by  num asc;";
            List<ConsumAbilityInfo> consumAbilityList = sqlMapper.selectList(getListSql, ConsumAbilityInfo.class);
            ShiroKit.setSessionAttr("consumAbilityList", consumAbilityList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getEconomicAbilityList() == null) {
            String getListSql = "select id, economic_ability from economic_ability_info order by num asc;";
            List<EconomicAbilityInfo> economicAbilityList = sqlMapper.selectList(getListSql, EconomicAbilityInfo.class);
            ShiroKit.getUser().setEconomicAbilityList(economicAbilityList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getCharactersList() == null) {
            String getListSql = "select id, characters from character_info order by num asc;";
            List<CharacterInfo> charactersList=sqlMapper.selectList(getListSql,CharacterInfo.class);
            ShiroKit.getUser().setCharactersList(charactersList);
        }
        if (ShiroKit.getUser().getConsumptionHabitsList() == null) {
            String getListSql = "select id, consumption_habits from consumption_habits_info order by  num asc;";
            List<ConsumptionHabitsInfo> consumptionHabitsList = sqlMapper.selectList(getListSql, ConsumptionHabitsInfo.class);
            ShiroKit.getUser().setConsumptionHabitsList(consumptionHabitsList);
        }
        model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
        model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("customerPhone", customerPhone);
        model.addAttribute("province", ShiroKit.getUser().getProvince());
        model.addAttribute("cities", ShiroKit.getUser().getCities());
        return PREFIX + "customer_receptionFor.html";
    }

    /**
     * 患者信息列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchCustomerInfo info) {
        if (info.getAbbreviation() == null || info.getAbbreviation() == "" || info.getAbbreviation() == "null") {
            return null;
        } else {
            Page<CustomerInfo> page = new PageFactory<CustomerInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CustomerInfo> list = service.selectPageListByQueryGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByQueryGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    /**
     * 会员查询
     */
    @RequestMapping("/customerMemberList")
    @ResponseBody
    public Object customerMemberList(SearchMembersUser info, HttpServletRequest request) {
        if (info.getOutpatientName() == "" || info.getOutpatientName() == null || info.getOutpatientName() == "null") {
            return null;
        } else {
            Page<MembersUser> page = new PageFactory<MembersUser>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<MembersUser> list = service.selectCustomerMemberList(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectCustomerMemberList(page, info);
                }
                page.setTotal(service.getQueryPagesMemberListCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    /**
     * 市场到前台修改渠道提交
     */
    @RequestMapping(value = "/update_channel", method = RequestMethod.POST)
    @ResponseBody
    public int updateChannel(String name, String sOneChannel, String reservationsId, String follower, String xfollower, String belonger, String xbelonger,
                             String sTwoChannel, String sThrChannel, String oneChannel, String outpatientName, String user, String num,
                             String twoChannel, String thrChannel, String remarks, String customerName, String customerPhone, String status) throws Exception {
        String operationTime = DateTimeKit.now();
        String sql = "INSERT INTO approval_process_info (reservations_id,status,`name`,follower,xfollower,belonger,xbelonger,`one_channel`,`two_channel`,`thr_channel`,`s_one_channel`,`s_two_channel`,`s_thr_channel`," +
                " `operation_time`, `remarks`,outpatient_name,user,customer_name ,customer_phone,submitter,channel_audit_level) VALUES" +
                "('" + reservationsId + "','" + status + "','" + name + "','" + follower + "','" + xfollower + "','" + belonger + "','" + xbelonger + "','" + oneChannel + "','" + twoChannel + "','" + thrChannel + "'," +
                "'" + sOneChannel + "','" + sTwoChannel + "','" + sThrChannel + "','" + operationTime + "','" + remarks + "'" +
                ",'" + outpatientName + "','" + user + "','" + customerName + "','" + customerPhone + "'," +
                " '" + ShiroKit.getUser().getAccount() + "','1');";
        sqlMapper.insert(sql);
        String sql1 = "select * from approval_process_info where operation_time='" + operationTime + "' and reservations_id='" + reservationsId + "'";
        ApprovalProcessInfo info = sqlMapper.selectOne(sql1, ApprovalProcessInfo.class);
        String upd = "update approval_process_iconinfo set process_id='" + info.getId() + "' ,num='' where num='" + num + "'";
        sqlMapper.update(upd);
        return 1;
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upLoadProcessCancal/{cri}")
    @ResponseBody
    public String upLoadProcess(@RequestPart("file") MultipartFile picture,
                                @PathVariable String cri) {
        String num = cri;
        //避免出现相同的图片名称  ids
        String ids = CommUtils.getUUID();
        String httpUrl = "yingxiang/" + ids + (picture.getOriginalFilename()).substring(1, 5) + ".png";
        try {
            aliyunOssUtil.pushSingleFile(picture, httpUrl);
//            FileUtils.copyInputStreamToFile(picture.getInputStream(), new File(realPath, ids + (picture.getOriginalFilename()).substring(1, 5) + ".png"));
            String sql = "insert into approval_process_iconinfo (num, image_path) values " +
                    "('" + num + "','" + MemberEnumConfig.ossphoeurl + httpUrl + "')";
            sqlMapper.insert(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return MemberEnumConfig.ossphoeurl + httpUrl;
    }

    //获取 图片
    @RequestMapping(value = "/getImgcancel", method = RequestMethod.POST)
    @ResponseBody
    public List<ApprovalProcessInfo> getImg(String num) throws Exception {
        String sql = "select * from approval_process_iconinfo where num='" + num + "' ";
        List<ApprovalProcessInfo> info2 = sqlMapper.selectList(sql, ApprovalProcessInfo.class);
        return info2;
    }

    /**
     * 到店 - 短信群发列表
     */
    @RequestMapping("/qfList")
    @ResponseBody
    public Object testrInfoqfList(SearchCustomerInfo info, HttpServletRequest request) {
        if (info.getAbbreviation() == null || info.getAbbreviation() == "" || info.getAbbreviation() == "null") {
            return null;
        } else {
            Page<CustomerInfo> page = new PageFactory<CustomerInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CustomerInfo> list = service.selectPageQfListByQueryGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageQfListByQueryGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesQfCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    //删除图片
    @RequestMapping(value = "/delteProcessCancel", method = RequestMethod.POST)
    @ResponseBody
    public int delteProcess(String id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "delete from approval_process_iconinfo where id='" + id + "'";
        return sqlMapper.delete(sql);
    }

    /**
     * 跳转到增加科室
     */
    @RequestMapping(value = "/add_TreatmentUnit/{id}")
    public String to_checkoutMethod(@PathVariable String id, Model model) {
        String sql = "select " +
                " ( " +
                " CASE t.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "t.* from " + ShiroKit.getUser().getCustomer_info() + " t where id='" + id + "' limit 0,1";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("CustomerInfo", CustomerInfo);
        model.addAttribute("customerId", id);
        return PREFIX + "add_TreatmentUnit.html";
    }

    /**
     * 查看会员是否存在
     */
    @RequestMapping(value = "/getMemberStatus", method = RequestMethod.POST)
    @ResponseBody
    public int getMemberStatus(String reservationsId) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String memberSql = "select a.reservations_id,a.open_id,b.open_id as openIdd from members_user a left join open_info b on a.open_id = b.open_id " +
                "where a.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(memberSql, MembersUser.class);
        if (membersUser == null) {
            return 1;
        } else {
            if (membersUser.getOpenId() == null || "".equals(membersUser.getOpenId()) || "null".equals(membersUser.getOpenId())
                    || membersUser.getOpenIdd() == null || "".equals(membersUser.getOpenIdd()) || "null".equals(membersUser.getOpenIdd())) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * 生产二维码
     */
    @RequestMapping(value = "/to_generateQrCode/{id}")
    public String to_generateQrCode(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String selecsql = "select id, reservations_id,customer_phone,customer_name from " + ShiroKit.getUser().getCustomer_info() + " a where id ='" + id + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selecsql, CustomerInfo.class);
        model.addAttribute("customerId", id);
        model.addAttribute("imgName", service.geturl(customerInfo));
        model.addAttribute("customerName", customerInfo.getCustomerName());
        model.addAttribute("customerPhone", customerInfo.getCustomerPhone());
        return PREFIX + "to_generateQrCode.html";
    }

    /**
     * 增加科室
     */
    @RequestMapping(value = "/add_TreatmentUnitValue", method = RequestMethod.POST)
    @ResponseBody
    public int add_TreatmentUnitValue(String initialization, String customerId, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set update_people='" + ShiroKit.getUser().getAccount() + "'," +
                "update_time='" + DateTimeKit.now() + "',treatment_unit=CONCAT(treatment_unit,'," + initialization + "') where id ='" + customerId + "' ;";
        return sqlMapper.update(sql);
    }

    /**
     * 跳转到修改科室
     */
    @RequestMapping(value = "/update_TreatmentUnit/{id}")
    public String update_TreatmentUnit(@PathVariable String id, Model model) {
        String sql = "select " +
                " ( " +
                " CASE a.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + id + "' limit 1";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("CustomerInfo", CustomerInfo);
        model.addAttribute("customerId", id);
        model.addAttribute("treatmentUnit", CustomerInfo.getTreatmentUnit());
        return PREFIX + "update_TreatmentUnit.html";
    }

    /**
     * 预约人数
     */
    @RequestMapping(value = "/getMakeNumer", method = RequestMethod.POST)
    @ResponseBody
    public List<CustomerInfo> getMakeNumer(String reservationsId, Model model) {
        String sql = "" +
                "(select '今天' as name,left(start_time,10) as yearday,substring(start_time,11,6) as startTime,substring(end_time,11,6) as endTime ," +
                "a.appointment_pay_service as appointmentPayService,a.doctor as doctor,a.id,a.reservations_id as reservationsId  " +
                "from " + ShiroKit.getUser().getCustomer_info() + " a where arrival_status!=8 and reservations_id='" + reservationsId + "' and left(start_time,10)=left(now(),10) ) " +
                "union all" +
                "(select '之后' as name,left(start_time,10) as yearday,substring(start_time,11,6) as startTime,substring(end_time,11,6) as endTime ," +
                "a.appointment_pay_service as appointmentPayService,a.doctor as doctor,a.id,a.reservations_id as reservationsId " +
                "from " + ShiroKit.getUser().getCustomer_info() + " a where arrival_status!=8 and reservations_id='" + reservationsId + "' and left(start_time,10)>left(now(),10) )" +
                "union all" +
                "(select '之前' as name,left(start_time,10) as yearday,substring(start_time,11,6) as startTime,substring(end_time,11,6) as endTime ," +
                "a.appointment_pay_service as appointmentPayService,a.doctor as doctor,a.id,a.reservations_id as reservationsId " +
                "from " + ShiroKit.getUser().getCustomer_info() + " a  where arrival_status!=8 and reservations_id='" + reservationsId + "' and left(start_time,10)<left(now(),10) );";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql, CustomerInfo.class);
        return customerInfoList;
    }

    /**
     * 判定科室登记
     */
    @RequestMapping(value = "/treatmentUnitGrade", method = RequestMethod.POST)
    @ResponseBody
    public int treatmentUnitGrade(String initialization, String customerId, String remarks, String treatmentUnitY, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlpy = "select ((select a.grade from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.department='" + initialization + "' limit 1)-" +
                "(select a.grade from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.department='" + treatmentUnitY + "' limit 1)) as grade from dual";
        PayServicedInfo py = sqlMapper.selectOne(sqlpy, PayServicedInfo.class);
        if (Integer.parseInt(py.getGrade()) > 0) {  //修改的科室等级大于原科室的等级需要审核
            return 1;
        } else {
            return 2;   //修改的科室等级小于原科室的等级 直接修改
        }
    }

    /**
     * 修改科室
     */
    @RequestMapping(value = "/update_TreatmentUnitValueOne", method = RequestMethod.POST)
    @ResponseBody
    public int update_TreatmentUnitValueOne(String initialization, String customerId, String remarks, String treatmentUnitY, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        int auditOfDept = ShiroKit.getUser().getAuditOfDept();
        if (auditOfDept == 1) {  //修改的科室等级大于原科室的等级需要审核
            String sql = "INSERT INTO  treatment_unitl_log (reservations_id,medical_record_number,customer_id,`customer_name`,`customer_phone`,`ytreatment_unitl`,`xtreatment_unitl`," +
                    " `remarks`,outpatient_name,add_time,status,add_people) VALUES" +
                    "('" + customerInfo.getReservationsId() + "','" + customerInfo.getMedicalRecordNumber() + "','" + customerInfo.getId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "','"
                    + customerInfo.getTreatmentUnit() + "','" + initialization + "','" + remarks + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                    + DateTimeKit.now() + "','待审核','" + ShiroKit.getUser().getAccount() + "');";
            return sqlMapper.insert(sql);
        } else {  //修改的科室等级大于原科室的等级不需要审核
            String sql = "INSERT INTO  treatment_unitl_log (reservations_id,medical_record_number,customer_id,`customer_name`,`customer_phone`,`ytreatment_unitl`,`xtreatment_unitl`," +
                    " `remarks`,outpatient_name,add_time,status,add_people) VALUES" +
                    "('" + customerInfo.getReservationsId() + "','" + customerInfo.getMedicalRecordNumber() + "','" + customerInfo.getId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "','"
                    + customerInfo.getTreatmentUnit() + "','" + initialization + "','" + remarks + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                    + DateTimeKit.now() + "','待审核','" + ShiroKit.getUser().getAccount() + "');";
            String upsql = "update " + ShiroKit.getUser().getCustomer_info() + " set treatment_unit='" + initialization + "' where id='" + customerId + "'";
            sqlMapper.update(upsql);
            return sqlMapper.insert(sql);
        }
    }

    /**
     * 修改科室
     */
    @RequestMapping(value = "/update_TreatmentUnitValueTwo", method = RequestMethod.POST)
    @ResponseBody
    public int update_TreatmentUnitValueTwo(String initialization, String customerId, String remarks, String treatmentUnitY, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set treatment_unit='" + initialization + "' where id='" + customerId + "'";
        return sqlMapper.update(sql);//修改的科室等级小于原科室的等级 直接修改
    }

    /**
     * 修改科室
     */
    @RequestMapping(value = "/update_TreatmentUnitValue1", method = RequestMethod.POST)
    @ResponseBody
    public int update_TreatmentUnitValue1(String initialization, String customerId, String remarks, String treatmentUnitY, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlpy = "select ((select a.grade from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.department='" + initialization + "' limit 1)-" +
                "(select a.grade from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.department='" + treatmentUnitY + "' limit 1)) as grade from dual";
        PayServicedInfo py = sqlMapper.selectOne(sqlpy, PayServicedInfo.class);
        if (Integer.parseInt(py.getGrade()) > 0) {  //修改的科室等级大于原科室的等级
            String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "'";
            CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
            int auditOfDept = ShiroKit.getUser().getAuditOfDept();
            if (auditOfDept == 1) {//修改的科室等级大于原科室的等级需要审核 插入日志
                String sqli = "INSERT INTO  treatment_unitl_log (reservations_id,medical_record_number,customer_id,`customer_name`,`customer_phone`,`ytreatment_unitl`,`xtreatment_unitl`," +
                        " `remarks`,outpatient_name,add_time,update_time,status,update_people,add_people) VALUES" +
                        "('" + customerInfo.getReservationsId() + "','" + customerInfo.getMedicalRecordNumber() + "','" + customerInfo.getId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "','"
                        + customerInfo.getTreatmentUnit() + "','" + initialization + "','" + remarks + "','"
                        + ShiroKit.getUser().getOutpatientName() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','待审核','"
                        + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "');";
                sqlMapper.insert(sqli);
                return 1;
            } else {//修改的科室等级大于原科室的等级不需要审核 插入日志 并直接修改
                String sqli = "INSERT INTO  treatment_unitl_log (reservations_id,medical_record_number,customer_id,`customer_name`,`customer_phone`,`ytreatment_unitl`,`xtreatment_unitl`," +
                        " `remarks`,outpatient_name,add_time,update_time,status,update_people,add_people) VALUES" +
                        "('" + customerInfo.getReservationsId() + "','" + customerInfo.getMedicalRecordNumber() + "','" + customerInfo.getId() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerPhone() + "','"
                        + customerInfo.getTreatmentUnit() + "','" + initialization + "','" + remarks + "','"
                        + ShiroKit.getUser().getOutpatientName() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','待审核','"
                        + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "');";
                sqlMapper.insert(sqli);
                String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set treatment_unit='" + initialization + "' where id='" + customerId + "'";
                sqlMapper.update(sql);
                return 2;
            }
        } else {
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set treatment_unit='" + initialization + "' where id='" + customerId + "'";
            sqlMapper.update(sql);
            return 2;
        }
    }

    /**
     * 修改科室
     */
    @RequestMapping(value = "/updateTreatmentUnit/{ids}")
    public String updateTreatmentUnit(@PathVariable String ids, Model model) {
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String sql1 = "select * from treatment_unitl_log where id='" + id + "'";
        TreatmentUnitlLogInfo customerInfo = sqlMapper.selectOne(sql1, TreatmentUnitlLogInfo.class);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        model.addAttribute("id", customerInfo.getId());
        return PREFIY + "customer_treatment_unitl.html";
    }

    /**
     * 修改科室
     */
    @RequestMapping(value = "/updateTreatmentUnit2", method = RequestMethod.POST)
    @ResponseBody
    public int updateTreatmentUnit2(String reservationsId, String id, String ytreatmentUnitl, String isno, String customerId,
                                    String xtreatmentUnitl, String remarks, Model model) {
        String selectSql2 = "select t.customer_name as customerName,t.start_time as startTime,t.customer_status as customerStatus,t.end_time as endTime,t.customer_phone as customerPhone," +
                "t.field_tc as fieldTc,t.doctor as doctor," +
                "t.appointment_pay_service as appointmentPayService from " + ShiroKit.getUser().getCustomer_info() + " t where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectSql2, CustomerInfo.class);
        if ("不同意".equals(isno)) {
            String sql1 = "update treatment_unitl_log set isno='" + isno + "', remarkss='" + remarks + "',update_people='" + ShiroKit.getUser().getAccount() + "'," +
                    "update_time='" + DateTimeKit.now() + "',status='已审核'  where id='" + id + "'";
            sqlMapper.update(sql1);
            String sq1 = "INSERT INTO `treatment_unit_auditor_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','科室审核','" + ShiroKit.getUser().getId() + "','" + customerInfo.getCustomerStatus() + "', '"
                    + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','" + ShiroKit.getUser().getAccount() + " 把 " + customerInfo.getCustomerName() + " 的科室:" + ytreatmentUnitl + " 修改为:" + ytreatmentUnitl + " 通过审核','" + customerId + "' );";
            return sqlMapper.insert(sq1);  //插入科室审批日志
        } else if ("同意".equals(isno)) {
            String sql1 = "update treatment_unitl_log set isno='" + isno + "', remarkss='" + remarks + "',update_people='" + ShiroKit.getUser().getAccount() + "'," +
                    "update_time='" + DateTimeKit.now() + "',status='已审核'  where id='" + id + "'";
            sqlMapper.update(sql1);
            String sql2 = "update " + ShiroKit.getUser().getCustomer_info() + " set treatment_unit='" + xtreatmentUnitl + "', update_time='" + DateTimeKit.now() + "'" +
                    " where id='" + customerId + "'";
            sqlMapper.update(sql2);
            String sq13 = "INSERT INTO `treatment_unit_auditor_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','科室审核','" + ShiroKit.getUser().getId() + "','" + customerInfo.getCustomerStatus() + "', '"
                    + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','" + ShiroKit.getUser().getAccount() + " 把 " + customerInfo.getCustomerName() + " 的科室:" + ytreatmentUnitl + " 修改为:" + xtreatmentUnitl + " 通过审核','" + customerId + "' );";
            return sqlMapper.update(sq13);  //插入科室审批日志
        }
        return 1;
    }

    /**
     * 跳转到修改媒介
     */
    @RequestMapping(value = "/update_medium/{id}")
    public String update_medium(@PathVariable String id, Model model) {
        String sql = "select " +
                " ( " +
                " CASE a.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + id + "'";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("customerInfo", CustomerInfo);
        model.addAttribute("customerId", id);
        return PREFIX + "update_medium.html";
    }

    /**
     * 修改个人信息
     */
    @RequestMapping(value = "/update_mediumValue", method = RequestMethod.POST)
    @ResponseBody
    public int update_mediumValue(String oneMedium2, String twoMedium2, String thrMedium2, String customerId, Model model) {
        String sql2 = "select " +
                " ( " +
                " CASE a.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + customerId + "'";
        CustomerInfo info = sqlMapper.selectOne(sql2, CustomerInfo.class);
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set one_medium ='" + oneMedium2 + "',two_medium='" + twoMedium2 + "'" +
                ",thr_medium='" + thrMedium2 + "',update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                + "' where id ='" + customerId + "' ;";
        String sqls = "update reservations_info set one_medium ='" + oneMedium2 + "',two_medium='" + twoMedium2 + "'" +
                ",thr_medium='" + thrMedium2 + "',update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                + "' where id ='" + info.getReservationsId() + "' ;";
        sqlMapper.update(sqls);
        String sq13 = "INSERT INTO `medium_log_info` ( `customer_name`,`customer_phone`,`person`, `createtime`,`one_medium1`,`two_medium1`,`thr_medium1`," +
                "one_medium2,two_medium2,thr_medium2) VALUES " +
                " ( '" + info.getCustomerName() + "', '" + info.getCustomerPhone() + "', '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "'," +
                "'" + info.getOneMedium() + "','" + info.getTwoMedium() + "','" + info.getThrMedium() +
                "', '" + oneMedium2 + "', '" + twoMedium2 + "','" + thrMedium2 + "');";
        sqlMapper.insert(sq13);//插入媒介修改日志
        return sqlMapper.update(sql);
    }

    /**
     * 跳转到设置无龋齿卡
     */
    @RequestMapping(value = "/updateChildrenCard/{id}")
    public String updateChildrenCard(@PathVariable String id, Model model) {
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + id + "'";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("customerInfo", CustomerInfo);
        return PREFIX + "updateChildrenCard.html";
    }

    /**
     * 设置无龋齿卡
     */
    @RequestMapping(value = "/updateChildrenCardOk", method = RequestMethod.POST)
    @ResponseBody
    public int updateChildrenCardOk(String reservationsId, String childrenCard, Model model) {
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set children_card ='" + childrenCard
                + "' where reservations_id ='" + reservationsId + "' ;";
        return sqlMapper.update(sql);
    }

    /**
     * 跳转到修改个人信息
     */
    @RequestMapping(value = "/update_CustomerInfo/{id}")
    public String update_CustomeInfo(@PathVariable String id, Model model) {
        String sql = "select " +
                " ( " +
                " CASE a.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + id + "'";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("consumAbilityList") == null) {
            String getListSql = "select id, consum_ability from consum_ability_info order by  num asc;";
            List<ConsumAbilityInfo> consumAbilityList = sqlMapper.selectList(getListSql, ConsumAbilityInfo.class);
            ShiroKit.setSessionAttr("consumAbilityList", consumAbilityList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getEconomicAbilityList() == null) {
            String getListSql = "select id, economic_ability from economic_ability_info order by num asc;";
            List<EconomicAbilityInfo> economicAbilityList = sqlMapper.selectList(getListSql, EconomicAbilityInfo.class);
            ShiroKit.getUser().setEconomicAbilityList(economicAbilityList);
        }
        if (ShiroKit.getUser().getCharactersList() == null) {
            String getListSql = "select id, characters from character_info order by num asc;";
            List<CharacterInfo> charactersList=sqlMapper.selectList(getListSql,CharacterInfo.class);
            ShiroKit.getUser().setCharactersList(charactersList);
        }
        if (ShiroKit.getUser().getConsumptionHabitsList() == null) {
            String getListSql = "select id, consumption_habits from consumption_habits_info order by  num asc;";
            List<ConsumptionHabitsInfo> consumptionHabitsList = sqlMapper.selectList(getListSql, ConsumptionHabitsInfo.class);
            ShiroKit.getUser().setConsumptionHabitsList(consumptionHabitsList);
        }
        model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
        model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
        model.addAttribute("customerInfo", CustomerInfo);
        model.addAttribute("customerId", id);
        return PREFIX + "update_CustomerInfo.html";
    }

    /**
     * 修改个人信息
     */
    @RequestMapping(value = "/update_CustomeInfoValue/{customerId}", method = RequestMethod.POST)
    @ResponseBody
    public int update_CustomeInfoValue(@Valid CustomerInfo info, @PathVariable String customerId, Model model) {
        String sql11 = "select count(1) as amount from " + ShiroKit.getUser().getCustomer_info() + " where upper(medical_record_number)=upper('" + info.getMedicalRecordNumber() + "') " +
                " and reservations_id !='" + info.getReservationsId() + "' ";
        CustomerInfo customer = sqlMapper.selectOne(sql11, CustomerInfo.class);
        CustomerInfo info1 = service.selectOneById(customerId);
        if (customer.getAmount() > 0) {
            return 0;
        } else {
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_name ='" + info.getCustomerName() + "'" +
                    ",birthday='" + info.getBirthday() + "'" +
                    ",age_range= " +
                    "(case " +
                    " WHEN (0<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<10) then '0-9' " +
                    " WHEN (10<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<20) then '10-19' " +
                    " WHEN (20<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<30) then '20-29' " +
                    " WHEN (30<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<40) then '30-39' " +
                    " WHEN (40<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<50) then '40-49' " +
                    " WHEN (50<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<60) then '50-59' " +
                    " WHEN (60<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<70) then '60-69' " +
                    " WHEN (70<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<80) then '70-79' " +
                    " WHEN (80<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<90) then '80-89' " +
                    " WHEN (90<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<100) then '90-99' " +
                    " else '99+' end)" +
                    ",customer_age=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS('" + info.getBirthday() + "')),'%Y')),customer_sex='" + info.getCustomerSex() + "'" +
                    ",medical_record_number='" + info.getMedicalRecordNumber() + "',referee='" + info.getReferee() + "',referee_ship='" + info.getRefereeShip() + "'" +
                    ",province='" + info.getProvince() + "',cities='" + info.getCities() + "',region='" + info.getRegion() + "',address='" + info.getAddress() + "'" +
                    ",occupation='" + info.getOccupation() + "',consum_ability='" + info.getConsumAbility() + "',consumption_habits='" + info.getConsumptionHabits() +
                    "',id_card_no='" + info.getIdCardNo() + "',fixed_telephone='" + info.getFixedTelephone() + "',qq_number='" + info.getQqNumber() +
                    "',wechat_Number='" + info.getWechatNumber() + "',email='" + info.getEmail() + "',zip_code='" + info.getZipCode() +
                    "',marital_status='" + info.getMaritalStatus() + "',is_have_children='" + info.getIsHaveChildren() + "',characters='" + info.getCharacters() +
                    "',remarks='" + info.getRemarks() + "',customer_sex_head='" + customerPublicService.getSexPt(info) + "' " +
                    " where reservations_id ='" + info.getReservationsId() + "';";
            String upsql = "update " + ShiroKit.getUser().getCustomer_info() + " set " +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now() + "' where id ='" + info.getId() + "';";

            if (!info.getMedicalRecordNumber().equals(info1.getMedicalRecordNumber())) {
                //插入号修改日志
                String sq11 = "INSERT INTO `customer_medical_number_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                        " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                        " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','修改','" + ShiroKit.getUser().getId() + "','" + info1.getCustomerStatus() + "', '"
                        + info1.getCustomerName() + "', '" + info1.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                        "','" + ShiroKit.getUser().getAccount() + " :修改了 " + info1.getCustomerName() + " 的病历号 ','" + info1.getId() + "','" + info1.getReservationsId() + "');";
                sqlMapper.insert(sq11);
                String sqlupodamesql1 = "update " + ShiroKit.getUser().getMedicalrecord_info() + " a set customer_phone=null where customer_phone='" + info1.getCustomerPhone() + "'";
                sqlMapper.update(sqlupodamesql1);
                String sqlupodamesql2 = "update " + ShiroKit.getUser().getMedicalrecord_info() + " a set customer_phone='" + info1.getCustomerPhone() + "' where CONCAT(a.prefix_part_one,a.prefix_part_two,a.num)='" + info.getMedicalRecordNumber() + "'";
                sqlMapper.update(sqlupodamesql2);
                String updsql1 = "update distinction_customer_status set medical_record_number='" + info.getMedicalRecordNumber() + "' where reservations_id='" + info1.getReservationsId() + "' and status=1 ";
                sqlMapper.update(updsql1);
                String updsql2 = "update reservations_info set identification_number='" + info.getMedicalRecordNumber() + "' where id='" + info1.getReservationsId() + "'";
                sqlMapper.update(updsql2);
                String updsql3 = "update reservations_infosc set identification_number='" + info.getMedicalRecordNumber() + "' where id='" + info1.getReservationsId() + "'";
                sqlMapper.update(updsql3);
            }
            sqlMapper.update(upsql);
            return sqlMapper.update(sql);
        }
    }

    /**
     * 修改个人信息
     */
    @RequestMapping(value = "/updateCustomeInfoValue", method = RequestMethod.POST)
    @ResponseBody
    public int updateCustomeInfoValue(CustomerInfo info, Model model) {
        String sql11 = "select count(1) as amount from " + ShiroKit.getUser().getCustomer_info() + " where upper(medical_record_number)=upper('" + info.getMedicalRecordNumber() + "') " +
                " and reservations_id !='" + info.getReservationsId() + "' ";
        CustomerInfo customer = sqlMapper.selectOne(sql11, CustomerInfo.class);
        String sql1 = "select id,reservations_id,one_medium,two_medium,thr_medium,medical_record_number from " + ShiroKit.getUser().getCustomer_info() + " where id='" + info.getId() + "'";
        CustomerInfo ccinfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        if (customer.getAmount() > 0 && !info.getMedicalRecordNumber().equals(ccinfo.getMedicalRecordNumber())) {
            return 0;
        } else {
            String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_name ='" + info.getCustomerName() + "'" +
                    ",birthday='" + info.getBirthday() + "'" +
                    ",age_range= " +
                    "(case " +
                    " WHEN (0<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<10) then '0-9' " +
                    " WHEN (10<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<20) then '10-19' " +
                    " WHEN (20<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<30) then '20-29' " +
                    " WHEN (30<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<40) then '30-39' " +
                    " WHEN (40<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<50) then '40-49' " +
                    " WHEN (50<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<60) then '50-59' " +
                    " WHEN (60<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<70) then '60-69' " +
                    " WHEN (70<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<80) then '70-79' " +
                    " WHEN (80<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<90) then '80-89' " +
                    " WHEN (90<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<100) then '90-99' " +
                    " else '99+' end)" +
                    ",customer_age='" + info.getCustomerAge() + "',customer_sex='" + info.getCustomerSex() + "',customer_sex_head='"+customerPublicService.getSexPt(info)+"'" +
                    ",medical_record_number='" + info.getMedicalRecordNumber() + "',referee='" + info.getReferee() + "',referee_ship='" + info.getRefereeShip() + "'" +
                    ",province='" + info.getProvince() + "',cities='" + info.getCities() + "',region='" + info.getRegion() + "',address='" + info.getAddress() + "'" +
                    ",occupation='" + info.getOccupation() + "',consum_ability='" + info.getConsumAbility() + "',consumption_habits='" + info.getConsumptionHabits() +
                    "',id_card_no='" + info.getIdCardNo() + "',fixed_telephone='" + info.getFixedTelephone() + "',yellow_number='" + info.getYellowNumber() + "',one_medium='" + info.getOneMedium() + "'" +
                    ",two_medium='" + info.getTwoMedium() + "',thr_medium='" + info.getThrMedium() + "',qq_number='" + info.getQqNumber() +
                    "',wechat_Number='" + info.getWechatNumber() + "',email='" + info.getEmail() + "',zip_code='" + info.getZipCode() +
                    "',marital_status='" + info.getMaritalStatus() + "',is_have_children='" + info.getIsHaveChildren() + "',characters='" + info.getCharacters() +
                    "',remarks='" + info.getRemarks() + "' where reservations_id ='" + info.getReservationsId() + "';";
            String upsql = "update " + ShiroKit.getUser().getCustomer_info() + " set " +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now() + "' where id ='" + info.getId() + "';";
            String updelsql = "update " + ShiroKit.getUser().getDeal_info() + " set orthodontic_number='" + info.getOrthodonticNumber() + "' " +
                    " where reservations_id ='" + info.getReservationsId() + "' and orthodontic_number='" + info.getOrthodonticNumberValue() + "';";
            if (info.getIsUpdaMediu() == 2) { //插入媒介修改日志
                String sq13 = "INSERT INTO `medium_log_info` ( `customer_name`,`customer_phone`,`person`, `createtime`,`one_medium2`,`two_medium2`,`thr_medium2`," +
                        "one_medium1,two_medium1,thr_medium1) VALUES " +
                        " ( '" + info.getCustomerName() + "', '" + info.getCustomerPhone() + "', '" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "'," +
                        "'" + info.getOneMedium() + "','" + info.getTwoMedium() + "','" + info.getThrMedium() +
                        "', '" + ccinfo.getOneMedium() + "', '" + ccinfo.getTwoMedium() + "','" + ccinfo.getThrMedium() + "');";
                sqlMapper.insert(sq13);
            }
            if (!info.getMedicalRecordNumber().equals(ccinfo.getMedicalRecordNumber())) {
                //插入号修改日志
                String sq11 = "INSERT INTO `customer_medical_number_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                        " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                        " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','修改','" + ShiroKit.getUser().getId() + "','" + info.getCustomerStatus() + "', '"
                        + info.getCustomerName() + "', '" + info.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                        "','" + ShiroKit.getUser().getAccount() + " :修改了 " + info.getCustomerName() + " 的病历号 ','" + info.getId() + "','" + info.getReservationsId() + "');";
                sqlMapper.insert(sq11);
                String sqlupodamesql1 = "update " + ShiroKit.getUser().getMedicalrecord_info() + " a set customer_phone=null where customer_phone='" + info.getCustomerPhone() + "'";
                sqlMapper.update(sqlupodamesql1);
                String sqlupodamesql2 = "update " + ShiroKit.getUser().getMedicalrecord_info() + " a set customer_phone='" + info.getCustomerPhone() + "' where CONCAT(a.prefix_part_one,a.prefix_part_two,a.num)='" + info.getMedicalRecordNumber() + "'";
                sqlMapper.update(sqlupodamesql2);
                String updsql1 = "update distinction_customer_status set medical_record_number='" + info.getMedicalRecordNumber() + "' where reservations_id='" + ccinfo.getReservationsId() + "' and status=1 ";
                sqlMapper.update(updsql1);
                String updsql2 = "update reservations_info set identification_number='" + info.getMedicalRecordNumber() + "' where id='" + ccinfo.getReservationsId() + "'";
                sqlMapper.update(updsql2);
                String updsql3 = "update reservations_infosc set identification_number='" + info.getMedicalRecordNumber() + "' where id='" + ccinfo.getReservationsId() + "'";
                sqlMapper.update(updsql3);
            }
            sqlMapper.update(upsql);
            sqlMapper.update(updelsql);
            return sqlMapper.update(sql);
        }
    }

    /**
     * 跳转到修改电话
     */
    @RequestMapping(value = "/update_phone/{id}")
    public String update_phone(@PathVariable String id, Model model) {
        String sql = "select " +
                " ( " +
                " CASE a.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + id + "'";
        CustomerInfo CustomerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("customerInfo", CustomerInfo);
        model.addAttribute("customerId", id);
        return PREFIX + "update_phone.html";
    }

    /**
     * 修改电话
     */
    @RequestMapping(value = "/setZphone", method = RequestMethod.POST)
    @ResponseBody
    public int setZphone(String customerPhone, String customerPhone2, String customerId, String reservationsId, Model model) {
        String sql1 = "select reservations_id from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + customerId + "' ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_phone ='" + customerPhone + "',customer_phone2='" + customerPhone2 + "'" +
                ",update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                + "' where reservations_id ='" + customerInfo.getReservationsId() + "' ;";
        String sqldist = "select a.id from distinction_customer_status a where a.reservations_id='" + reservationsId + "' and deal_status='未成交'";
        List<PayServicedInfo> sqldistl = sqlMapper.selectList(sqldist, PayServicedInfo.class);
        if(sqldistl.size()>0){  //之前未成交，本次成交了，修改时间状态
            String up1 = "update distinction_customer_status set deal_status='已成交',update_time='" + DateTimeKit.now() + "' where reservations_id='" + reservationsId + "' " +
                    " and status=1  and arrival_store='" + ShiroKit.getUser().getOutpatientName() + "';";
            sqlMapper.update(up1);
        }
        String sql3 = "update members_user set account ='" + customerPhone + "' ,phone='" + customerPhone +
                "' where reservations_id ='" + customerInfo.getReservationsId() + "' ;";
        sqlMapper.update(sql3);
        return sqlMapper.update(sql);
    }

    /**
     * 删除电话
     */
    @RequestMapping(value = "/deletePhone", method = RequestMethod.POST)
    @ResponseBody
    public int deletePhone(String customerPhone, String customerPhone2, String customerId, Model model) {
        String sql3;
        String sql = "select id from " + ShiroKit.getUser().getCustomer_info() + " a where id='" + customerId + "' and customer_phone like '%" + customerPhone + "%'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (customerInfo != null) {
            sql3 = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_phone='" + customerPhone2 + "',customer_phone2=''," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where id ='" + customerId + "' ;";
        } else {
            sql3 = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_phone2=''," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where id ='" + customerId + "' ;";
        }
        return sqlMapper.update(sql3);
    }

    /**
     * 添加电话
     */
    @RequestMapping(value = "/addPhone", method = RequestMethod.POST)
    @ResponseBody
    public int addPhone(String customerPhone3, String customerId, Model model) {
        String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + "  where id ='" + customerId + "' ;";
        CustomerInfo info = sqlMapper.selectOne(sql1, CustomerInfo.class);
        String sql = "select id from reservations_info where (customer_phone ='" + customerPhone3 + "' or customer_phone2='" + customerPhone3 + "') and " +
                " id!='" + info.getReservationsId() + "' limit 1;";
        CustomerInfo infos = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (infos != null) {//查询已有手机号的预约集合
            List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(customerPhone3);
            int count = existList.size();
            customerPhone3 = customerPhone3 + "+" + count;
        }
        if (info.getCustomerPhone2() != null) {
            String sql3 = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_phone2=concat(customer_phone2,'," + customerPhone3 + "')," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where reservations_id ='" + info.getReservationsId() + "' ;";
            String sql32 = "update reservations_info set customer_phone2=concat(customer_phone2,'," + customerPhone3 + "')," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where id ='" + info.getReservationsId() + "' ;";
            sqlMapper.update(sql32);
            return sqlMapper.update(sql3);
        } else {
            String sql3 = "update " + ShiroKit.getUser().getCustomer_info() + " set customer_phone2='" + customerPhone3 + "'," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where reservations_id ='" + info.getReservationsId() + "' ;";
            String sql33 = "update reservations_info set customer_phone2='" + customerPhone3 + "'," +
                    "update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                    + "' where id ='" + info.getReservationsId() + "' ;";
            sqlMapper.update(sql33);
            return sqlMapper.update(sql3);
        }
    }

    /**
     * 添加到店客户 匹配市场初到
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public int add(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id from " + ShiroKit.getUser().getCustomer_info() + " a where arrival_status!=8 and a.customer_name='" + info.getCustomerName() + "' " +
                "and a.customer_phone='" + info.getCustomerPhone() + "' and  " +
                "left(a.arrival_time,10)=left(curdate(),10) ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        if (customerInfo != null) {
            return 0;
        } else {
            info.setMedicalRecordNumber(service.getMedicalRecordNumbers(info.getCustomerPhone(), ShiroKit.getUser().getMedicalrecord_info()));
            reservationsService.insertCustomerStatus(info);   //加入客户状态表
            String selectsql = "select id,follower,filing_time,archiving,first_visit_date ,customer_phone2,customer_phone," +
                    " one_medium as oneMedium ,two_medium as twoMedium,thr_medium as thrMedium,one_channel as oneChannel,two_channel as twoChannel ,thr_channel as thrChannel " +
                    " from reservations_info where id='" + info.getReservationsId() + "' limit 0,1";
            ReservationsInfo reservations = sqlMapper.selectOne(selectsql, ReservationsInfo.class);
            if (reservations != null) {//跟进人，为空，建档人给归属人
                if (StringUtil.isEmpty(reservations.getFollower())) {
                    String sql1 = "update reservations_info set belonger='" + reservations.getArchiving() + "' where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set belonger='" + reservations.getArchiving() + "' where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sqlsc);
                    info.setScarchiving(reservations.getArchiving());
                    info.setCustomerPhone2(reservations.getCustomerPhone2());
                    info.setMarketFilingTime(reservations.getFilingTime());
                    service.insert(info);
                } else {
                    //跟进人，不为空或待定，跟进人给归属人
                    String sql1 = "update reservations_info set belonger='" + reservations.getFollower() + "' where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set belonger='" + reservations.getFollower() + "' where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sqlsc);
                    info.setScarchiving(reservations.getFollower());
                    info.setCustomerPhone2(reservations.getCustomerPhone2());
                    info.setMarketFilingTime(reservations.getFilingTime());
                    service.insert(info);
                }
                if (StringUtil.isEmpty(reservations.getFirstVisitDate())) {
                    String sql1 = "update reservations_info set status='到店',outpatient_name='" + info.getArrivalStore() + "',filling_status='到店沉淀期'," +
                            "tc_name='" + info.getFieldTc() + "',first_visit_date='" + DateTimeKit.now() + "'," +
                            "identification_number='" + info.getMedicalRecordNumber() + "',arrival_store='" + ShiroKit.getUser().getOutpatientName() + "' " +
                            "where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set status='到店',outpatient_name='" + info.getArrivalStore() + "',filling_status='到店沉淀期'," +
                            "tc_name='" + info.getFieldTc() + "',first_visit_date='" + DateTimeKit.now() + "'," +
                            "identification_number='" + info.getMedicalRecordNumber() + "',arrival_store='" + ShiroKit.getUser().getOutpatientName() + "' " +
                            "where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sqlsc);
                } else {
                    String sql1 = "update reservations_info set status='到店',outpatient_name='" + info.getArrivalStore() + "',filling_status='到店沉淀期'," +
                            "tc_name='" + info.getFieldTc() + "',identification_number='" + info.getMedicalRecordNumber() + "',arrival_store='"
                            + ShiroKit.getUser().getOutpatientName() + "'  where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set status='到店',outpatient_name='" + info.getArrivalStore() + "',filling_status='到店沉淀期'," +
                            "tc_name='" + info.getFieldTc() + "',identification_number='" + info.getMedicalRecordNumber() + "',arrival_store='"
                            + ShiroKit.getUser().getOutpatientName() + "'  where id = '" + info.getReservationsId() + "'";
                    sqlMapper.update(sqlsc);
                }
                String updasql = "update " + ShiroKit.getUser().getCustomer_info() + " a set scarchiving='" + info.getScarchiving() + "',reservations_id='" + reservations.getId() + "'" +
                        ",one_channel='" + reservations.getOneChannel() + "',two_channel='" + reservations.getTwoChannel() + "',thr_channel='" + reservations.getThrChannel() + "'" +
                        ",one_medium='" + info.getOneMedium() + "',two_medium='" + info.getTwoMedium() + "',thr_medium='" + info.getThrMedium() + "'," +
                        "first_visit_date='" + DateTimeKit.now() + "',customer_phone2='" + reservations.getCustomerPhone2() + "' where customer_phone = '" + reservations.getCustomerPhone() + "'";
                sqlMapper.update(updasql);
            } //插入视图改动日志 新诊挂号
            String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','匹配市场预约初诊到店','" + ShiroKit.getUser().getId() + "','" + info.getCustomerStatus() + "', '"
                    + info.getCustomerName() + "', '" + info.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','匹配市场预约初诊到店：预约->挂号','" + info.getId() + "','" + info.getReservationsId() + "');";
            sqlMapper.insert(sq11);   //门诊预约初诊到店挂号
            return 1;
        }
    }

    /**
     * 添加到店客户 市场匹配
     */
    @RequestMapping(value = "/oneKeyLightenUp", method = RequestMethod.POST)
    @ResponseBody
    public int oneKeyLightenUp(String id, String ekyNumber, String outpatientName) throws Exception {
        String sql11 = "select * from reservations_info where id='" + id + "'";
        ReservationsInfo info = sqlMapper.selectOne(sql11, ReservationsInfo.class);
        String sqld = "select * from dept where simplename='" + outpatientName + "'";
        Dept dept = sqlMapper.selectOne(sqld, Dept.class);
        if (info != null) {
            info.setAbbreviation(dept.getAbbreviation());
            info.setEkyNumber(ekyNumber);
            info.setArrivalStore(outpatientName);
            info.setReservationsId(id);
            //跟进人，为空，建档人给归属人
            if (StringUtil.isEmpty(info.getFollower())) {
                String sql1 = "update reservations_info set belonger='" + info.getArchiving() + "' where id = '" + info.getId() + "'";
                sqlMapper.update(sql1);
                String sqlsc = "update reservations_infosc set belonger='" + info.getArchiving() + "' where id = '" + info.getId() + "'";
                sqlMapper.update(sqlsc);
                service.insertsc(info);
            } else if (!StringUtil.isEmpty(info.getFollower()) || "待定".equals(info.getFollower())) {
                //跟进人，不为空或待定，跟进人给归属人
                String sql1 = "update reservations_info set belonger='" + info.getFollower() + "' where id = '" + info.getId() + "'";
                sqlMapper.update(sql1);
                String sqlsc = "update reservations_infosc set belonger='" + info.getFollower() + "' where id = '" + info.getId() + "'";
                sqlMapper.update(sqlsc);
                service.insertsc(info);
            }
        }
        return 1;
    }

    /**
     * 添加到店客户(直接上门)
     */
    @RequestMapping(value = "/addNatureCustomer")
    @ResponseBody
    public MembersArriveInfo addCustomer(@Valid CustomerInfo info, BindingResult result, Model model) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String id = "";
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        if (info.getReferee() != null && info.getReferee() != "") {
            id = "ldx" + CommUtils.getUUID() + randomNumber;
//            info.setOneChannel(info.getOneMedium());
//            info.setTwoChannel(info.getTwoMedium());
//            info.setThrChannel(info.getThrMedium());
        } else {
            id = "zd" + CommUtils.getUUID() + randomNumber;
        }
        info.setReservationsId(id);
        String infocustomer = "";
        String customerid = "";
        String sql = " select id from reservations_info where customer_phone='" + info.getCustomerPhone() + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String sql2 = " select id from " + ShiroKit.getUser().getCustomer_info() + " where  customer_phone like '%" + info.getCustomerPhone() + "%'" +
                " and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10" +
                " and arrival_time is not null limit 1";
        CustomerInfo customerInfo2 = sqlMapper.selectOne(sql2, CustomerInfo.class);
        MembersArriveInfo membersArriveInfos = new MembersArriveInfo();
        if (customerInfo2 != null || customerInfo != null) {
            if (!"本人".equals(info.getPhoneSharShip())) {
                //查询已有手机号的预约集合
                List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
                int count = existList.size();
                String customerPhone = info.getCustomerPhone() + "+" + count;
                info.setCustomerPhone(customerPhone);
                String time = DateTimeKit.now();
                info.setMedicalRecordNumber(service.getMedicalRecordNumbers(customerPhone, ShiroKit.getUser().getMedicalrecord_info()));
                reservationsService.insert(info);
                reservationsService.insertCustomerStatus(info);   //加入客户状态表
                info.setDoctor("未指定医生");
                info.setStartTime(time);
                info.setFilingTime(time);
                service.insert(info);
            } else {
                membersArriveInfos.setIds("已存在");
                return membersArriveInfos;
            }
        } else {
            if (!"本人".equals(info.getPhoneSharShip())) {
                //查询已有手机号的预约集合
                List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
                int count = existList.size();
                String customerPhone = info.getCustomerPhone() + "+" + count;
                info.setCustomerPhone(customerPhone);
            }
            if ("预约".equals(info.getCustomerStatus())) {
                String time = DateTimeKit.now();
                info.setFilingTime(time);
                infocustomer = service.insert2(info);  //前台新建客户
                model.addAttribute("customerId", infocustomer.split(",")[1]);
                customerid = infocustomer.split(",")[1];
            } else {
                String time = DateTimeKit.now();
                info.setMedicalRecordNumber(service.getMedicalRecordNumbers(info.getCustomerPhone(), ShiroKit.getUser().getMedicalrecord_info()));
                reservationsService.insert(info);
                reservationsService.insertCustomerStatus(info);   //加入客户状态表
                info.setDoctor("未指定医生");
                info.setStartTime(time);
                info.setFilingTime(time);
                service.insert(info);
            }
        }
        membersArriveInfos = service.memberDistinguishInUp(id);
        membersArriveInfos.setIds("1" + "," + id + "," + customerid);
        return membersArriveInfos;
    }

    /**
     * 添加到店客户(一人多号)
     */
    @RequestMapping(value = "/addOnemuchCustomerSubmit")
    @ResponseBody
    public MembersArriveInfo addOnemuchCustomerSubmit(@Valid CustomerInfo info, BindingResult result, Model model) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String id = "";
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        if (info.getReferee() != null && info.getReferee() != "") {
            id = "ldx" + CommUtils.getUUID() + randomNumber;
        } else {
            if ("直接上门".equals(info.getOneChannel())) {
                id = "zd" + CommUtils.getUUID() + randomNumber;
            } else {
                id = "sc" + CommUtils.getUUID() + randomNumber;
            }
        }
        info.setReservationsId(id);
        String infocustomer = "";
        String customerid = "";
        String sql = " select id from reservations_info where customer_phone='" + info.getCustomerPhone() + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String sql2 = " select id from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone like '%" + info.getCustomerPhone() + "%' limit 1";
        CustomerInfo customerInfo2 = sqlMapper.selectOne(sql2, CustomerInfo.class);
        info.setArchiving(info.getArchiving());
        info.setFollower(info.getArchiving());
        info.setBelongers(info.getArchiving());
        info.setScarchiving(info.getArchiving());
        MembersArriveInfo membersArriveInfos = new MembersArriveInfo();
        if (customerInfo2 != null || customerInfo != null) {
            if (!"本人".equals(info.getPhoneSharShip())) {
                //查询已有手机号的预约集合
                List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
                int count = existList.size();
                String customerPhone = info.getCustomerPhone() + "+" + count;
                info.setCustomerPhone(customerPhone);
                String time = DateTimeKit.now();
                info.setMedicalRecordNumber(service.getMedicalRecordNumbers(customerPhone, ShiroKit.getUser().getMedicalrecord_info()));
                reservationsService.insert(info);
                reservationsService.insertCustomerStatus(info);   //加入客户状态表
                info.setDoctor("未指定医生");
                info.setStartTime(time);
                info.setFilingTime(time);
                service.insert(info);
            } else {
                membersArriveInfos.setIds("已存在");
                return membersArriveInfos;
            }
        } else {
            if (!"本人".equals(info.getPhoneSharShip())) {
                //查询已有手机号的预约集合
                List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
                int count = existList.size();
                String customerPhone = info.getCustomerPhone() + "+" + count;
                info.setCustomerPhone(customerPhone);
            }
            if ("预约".equals(info.getCustomerStatus())) {
                String time = DateTimeKit.now();
                info.setFilingTime(time);
                infocustomer = service.insert2(info);  //前台新建客户
                model.addAttribute("customerId", infocustomer.split(",")[1]);
                customerid = infocustomer.split(",")[1];
            } else {
                String time = DateTimeKit.now();
                info.setMedicalRecordNumber(service.getMedicalRecordNumbers(info.getCustomerPhone(), ShiroKit.getUser().getMedicalrecord_info()));
                reservationsService.insert(info);
                reservationsService.insertCustomerStatus(info);   //加入客户状态表
                info.setDoctor("未指定医生");
                info.setStartTime(time);
                info.setFilingTime(time);
                service.insert(info);
            }
        }
        model.addAttribute("reservationsId", id);
        membersArriveInfos = service.memberDistinguishInUp(id);
        membersArriveInfos.setIds("1" + "," + id + "," + customerid);
        return membersArriveInfos;
    }

    /**
     * 添加到店客户
     */
    @RequestMapping(value = "/getNatureCustomer", method = RequestMethod.POST)
    @ResponseBody
    public CustomerInfo getNatureCustomer(String customerId, Model model) throws Exception {
        String sql = " select customer_name as customerName,customer_age as customerAge," +
                " ( " +
                " CASE customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex," +
                "customer_phone as customerPhone from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    /**
     * 删除预约客户
     */
    @RequestMapping(value = "/toVoid", method = RequestMethod.POST)
    @ResponseBody
    public int toVoid(String toVoidremarks, String customerId) throws Exception {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setToVoidremarks(toVoidremarks);
        customerInfo.setId(customerId);
        return service.toVoid(customerInfo);
    }

    @RequestMapping(value = "/to_referee")
    public String to_archiving(Model model) {
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "referee.html";
    }

    @RequestMapping(value = "/getReferee", method = RequestMethod.POST)
    @ResponseBody
    public List<UserDto> getArchiving(String name) throws Exception {
        String sql = "select  t.customer_name as account,t.reservations_id as reservationsId from " + ShiroKit.getUser().getCustomer_info() + " t where t.customer_name like '%" + name + "%'" +
                " or t.customer_phone like '%" + name + "%' or t.szm like '%" + name + "%' group by t.reservations_id ";
        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
        return list;
    }

    //积分转诊人
    @RequestMapping(value = "/getRefereeScore", method = RequestMethod.POST)
    @ResponseBody
    public List<UserDto> getRefereeScore(String name) throws Exception {
        String sql = "select t.customer_name as account,t.reservations_id as reservationsId" +
                " from distinction_customer_status t " +
                " where t.customer_name like '%" + name + "%'" +
                " or t.customer_phone like '%" + name + "%' and status=1 group by t.reservations_id ";
        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
        return list;
    }

    /**
     * 医生/TC添加看诊记录
     */
    @RequestMapping(value = "/add_diagnosisContent1", method = RequestMethod.POST)
    @ResponseBody
    public int add_diagnosisContent1(String id, String reservationsId, String doctor, String diagnosisContent) throws Exception {
        String sql = "insert into  `tc_diagnosis_info` (`customer_id`,`reservations_id`,`tc_name`,`diagnosis_content`,`diagnosis_time`,outpatient_name) VALUES" +
                "('" + id + "','" + reservationsId + "','" + ShiroKit.getUser().getAccount() + "','"
                + diagnosisContent + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "');";
        sqlMapper.insert(sql);
        return consultantService.updateDiagnosisStatus(reservationsId);
    }

    /**
     * /**
     * 添加回访记录
     */
    @RequestMapping(value = "/add_isRevisit")
    @ResponseBody
    public int addIsRevisit(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String appointmentTime = "";
        if (info.getAppointmentTime() == null || info.getAppointmentTime() == "") {
            appointmentTime = "null";
        } else {
            appointmentTime = "'" + info.getAppointmentTime() + "'";
        }
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set expenditure_project = '" + info.getExpenditureProject() + "', cause_of_no_return_visit='" + info.getCauseOfNoReturnVisit() + "',is_return_visit= 1,follow_status='" + info.getFollowStatus() + "',consumption_status='" + info.getConsumptionStatus() + "'," +
                "remarks_of_return_visit='" + info.getRemarksOfReturnVisit() + "',reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                " where reservations_id='" + info.getReservationsId() + "'";
        consultantService.updateDiagnosisStatus(info.getId());
        String sql2 = "update `reservations_info` set expenditure_project = '" + info.getExpenditureProject() + "' where id ='" + info.getReservationsId() + "' ";
        sqlMapper.update(sql2);
        sqlMapper.update(sql);
        return consultantService.insert(info);
    }

    /**
     * TC 预约回访提交
     */
    @RequestMapping(value = "/add_yu_isRevisit")
    @ResponseBody
    public int addYuIsRevisit(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String appointmentTime = "";
        if (info.getAppointmentTime() == null || info.getAppointmentTime() == "") {
            appointmentTime = "null";
        } else {
            appointmentTime = "'" + info.getAppointmentTime() + "'";
        }
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set follow_status='" + info.getFollowStatus1() + "',consumption_status='" + info.getConsumptionStatus1() + "'," +
                "reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + " " +
                " where reservations_id='" + info.getReservationsId() + "'";
        info.setAppointmentTime(appointmentTime);
        if ("1".equals(info.getIsNew())) {
        } else {
            consultantService.insertReturnVisits(info);
        }
        return sqlMapper.update(sql);
    }

    /**
     * 患者手机号查询信息
     */
    @RequestMapping(value = "/patientByPhone/{cri}")
    public String patientByPhone(@PathVariable String cri, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String customerPhone = cri.split(",")[0];
        String customerName = cri.split(",")[1];
        String sql = "select t.quarters as address ,t.customer_sex as customerSex,t.* from reservations_info t " +
                "where customer_phone like '%" + customerPhone + "%' " +
                "order by filing_time desc limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        model.addAttribute("province", ShiroKit.getUser().getProvince());
        model.addAttribute("cities", ShiroKit.getUser().getCities());
        if (reservationsInfo != null) {
            if ("null".equals(reservationsInfo.getOccupation())) {
                reservationsInfo.setOccupation("");
            }
            model.addAttribute("customerInfo", reservationsInfo);
            model.addAttribute("customerPhone", reservationsInfo.getCustomerPhone());
            return PREFIX + "customer_updateInformation.html";
        } else {
            String sql2 = "select  ( " +
                    " CASE t.customer_sex " +
                    " WHEN 1 THEN " +
                    " '男' " +
                    " WHEN 2 THEN " +
                    " '女' " +
                    " ELSE " +
                    " '未知' " +
                    " END " +
                    " ) as sex  ,t.* from " + ShiroKit.getUser().getCustomer_info() + " t " +
                    "where  customer_phone like '%" + customerPhone + "%' and customer_name ='" + customerName + "'" +
                    " order by  create_appointment_time desc limit 0,1";
            CustomerInfo info = sqlMapper.selectOne(sql2, CustomerInfo.class);
            if (info != null) {
                model.addAttribute("customerInfo", info);
                model.addAttribute("customerPhone", info.getCustomerPhone());
                return PREFIX + "customer_updateInformation.html";
            } else {
                model.addAttribute("customerPhone", customerPhone);
                model.addAttribute("customerName", customerName);
                return PREFIX + "customer_addInformation.html";
            }
        }
    }

    //录入患者信息
    @RequestMapping(value = "/saveInformation", method = RequestMethod.POST)
    @ResponseBody
    public int saveInformation(String customerName, String customerPhone, String wechatNumber, String occupation, String sex, String about,
                               String age, String regioni, String provincei, String citiesi, String medicalReasons, String selectReasons, String address,
                               String phoneSharShip) throws Exception {
        String sql = "select * from medium where mediumname='" + selectReasons + "' and length(pids)>9   group by mediumname limit 0,1";
        Medium medium = sqlMapper.selectOne(sql, Medium.class);
        Integer pid = 110;
        if (medium != null) {
            pid = medium.getPid();
        }
        String sql2 = "select * from medium where id='" + pid + "' and length(pids)>5  group by mediumname limit 0,1";
        Medium medium2 = sqlMapper.selectOne(sql2, Medium.class);
        String mediumname2 = "直接上门";
        if (medium2 != null) {
            mediumname2 = medium2.getMediumname();
        }
        String sql3 = "select * from medium where id='" + medium2.getPid() + "' group by mediumname limit 0,1";
        Medium medium3 = sqlMapper.selectOne(sql3, Medium.class);
        String mediumname3 = "直接上门";
        if (medium3 != null) {
            mediumname3 = medium3.getMediumname();
        }
        String id = CommUtils.getUUID();
        //预约号
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        String reservationsId = "zd" + CommUtils.getUUID() + randomNumber;
        if (wechatNumber == null || wechatNumber == "") {
            wechatNumber = "null";
        } else {
            wechatNumber = "'" + wechatNumber + "'";
        }
        String sql1 = " select max(yellow_number) as yellowNumber from " + ShiroKit.getUser().getCustomer_info() + " ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        //设置黄页编号
        String yellowNumbers = "0000123";
        /*if (customerInfo != null) {
            if (StringUtil.isNotEmpty(customerInfo.getYellowNumber()) && !"null".equals(customerInfo.getYellowNumber())) {
                yellowNumbers = Integer.parseInt(customerInfo.getYellowNumber()) + 1;
            }
        }*/
        //查询已有手机号的预约集合
        List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(customerPhone);
        int count = existList.size();
        if (!"本人".equals(phoneSharShip)) {
            customerPhone = customerPhone + "+" + count;
        }
        String sql21 = "select id,first_visit_date from reservations_info where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql21, ReservationsInfo.class);
        String firstVisitDate = "";
        if (reservationsInfo != null) {
            if (reservationsInfo.getFirstVisitDate() == null || reservationsInfo.getFirstVisitDate() == "") {
                firstVisitDate = "'" + DateTimeKit.now() + "'";
            } else {
                firstVisitDate = "'" + reservationsInfo.getFirstVisitDate() + "'";
            }
        } else {
            firstVisitDate = "'" + DateTimeKit.now() + "'";
        }
        String sqladd = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`reservations_id`,`first_visit_date`,`deal_status`, " +
                "`customer_name`,`one_medium`,`two_medium`,`thr_medium`,`one_channel`,`two_channel`,`thr_channel`," +
                " `customer_sex`, `customer_age`, `wechat_number`, `archiving`," +
                " `doctor`, `country`, `province`, `cities`, `region`,`occupation`," +
                "  `filing_time`,`customer_phone`,`start_time`,`end_time`,create_appointment_time,arrival_store," +
                "medical_reasons,select_reasons,yellow_number,address,phone_shar_ship,szm) values " +
                "('" + id + "','" + reservationsId + "'," + firstVisitDate + ",'未开单','" + customerName + "'," +
                "'" + mediumname3 + "','" + mediumname2 + "','" + selectReasons + "','直接上门','直接上门','直接上门', " +
                " '" + sex + "', '" + age + "', " + wechatNumber + ",'" + ShiroKit.getUser().getAccount() + "'," +
                " '未指定医生','中国','" + provincei + "', '" + citiesi + "','" + regioni + "','" + occupation + "' ," +
                " '" + DateTimeKit.now() + "'," + " '" + customerPhone + "','" + customerPublicService.getStartTime() + "','" + customerPublicService.getEndTime()
                + "','" + DateTimeKit.now() + "' ,'" + ShiroKit.getUser().getOutpatientName() + "','"
                + medicalReasons + "','" + selectReasons + "','" + yellowNumbers + "','" + address + "','" + phoneSharShip + "',firstconcats('" + customerName + "'))";
        return sqlMapper.insert(sqladd);
    }

    //复诊修改患者信息
    @RequestMapping(value = "/updateInformation", method = RequestMethod.POST)
    @ResponseBody
    public int updateInformation(String customerName, String customerPhone,
                                 String wechatNumber, String occupation, String sex, String about,
                                 String age, String regioni, String provincei, String citiesi, String phoneSharShip,
                                 String medicalReasons, String selectReasons, String address) throws Exception {
        String sqlm1 = "select * from medium where mediumname='" + selectReasons + "' and length(pids)>9  group by mediumname limit 0,1";
        Medium medium = sqlMapper.selectOne(sqlm1, Medium.class);
        Integer pid = 110;
        if (medium != null) {
            pid = medium.getPid();
        }
        String sqlm2 = "select * from medium where id='" + pid + "'  and length(pids)>5  group by mediumname limit 0,1";
        Medium medium2 = sqlMapper.selectOne(sqlm2, Medium.class);
        String mediumname2 = "直接上门";
        if (medium2 != null) {
            mediumname2 = medium2.getMediumname();
        }
        String sqlm3 = "select * from medium where id='" + medium2.getPid() + "' group by mediumname limit 0,1";
        Medium medium3 = sqlMapper.selectOne(sqlm3, Medium.class);
        String mediumname3 = "直接上门";
        if (medium3 != null) {
            mediumname3 = medium3.getMediumname();
        }
        String sql1 = " select max(yellow_number) as yellowNumber from " + ShiroKit.getUser().getCustomer_info() + " ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        //设置黄页编号
        String yellowNumbers = "0000123";
        /*if (customerInfo != null) {
            if (StringUtil.isNotEmpty(customerInfo.getYellowNumber()) && !"null".equals(customerInfo.getYellowNumber())) {
                yellowNumbers = Integer.parseInt(customerInfo.getYellowNumber()) + 1;
            }
        }*/
        //查询已有手机号的预约集合
        List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(customerPhone);
        int count = existList.size();
        if (!"本人".equals(phoneSharShip)) {
            customerPhone = customerPhone + "+" + count;
            return this.saveInformation(customerName, customerPhone, wechatNumber, occupation,
                    sex, about, age, regioni, provincei, citiesi,
                    medicalReasons, selectReasons, address, phoneSharShip);
        } else {
            String sql = "select id from reservations_info where customer_phone='" + customerPhone + "' limit 0,1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
            if (reservationsInfo != null) {
                String id = CommUtils.getUUID();
                String sql3 = "select id from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone='" + customerPhone + "' and " +
                        "left(create_appointment_time,10) ='" + customerPublicService.getStartTime().substring(0, 10) + "'";
                List<CustomerInfo> cinfo2 = sqlMapper.selectList(sql3, CustomerInfo.class);
                if (cinfo2.size() > 0) {
                    String sqlupd = "update " + ShiroKit.getUser().getCustomer_info() + "  set  " +
                            "start_time='" + customerPublicService.getStartTime() + "',end_time='" + customerPublicService.getEndTime() + "'," +
                            "archiving='" + ShiroKit.getUser().getAccount() + "'," +
                            "create_appointment_time = '" + DateTimeKit.now() + "'," +
                            "customer_name= '" + customerName + "'," +
                            "customer_age= '" + age + "'," +
                            "customer_sex= '" + sex + "'," +
                            "occupation= '" + occupation + "'," +
                            "address= '" + address + "'," +
                            "province= '" + provincei + "'," +
                            "cities= '" + citiesi + "'," +
                            "region= '" + regioni + "'," +
                            "medical_reasons= '" + medicalReasons + "'," +
                            "one_medium= '" + mediumname3 + "'," +
                            "two_medium= '" + mediumname2 + "'," +
                            "thr_medium= '" + selectReasons + "' " +
                            " where customer_phone='" + customerPhone + "'" +
                            " and left(start_time,10)='" + customerPublicService.getStartTime().substring(0, 10) + "'";
                    return sqlMapper.update(sqlupd);
                } else {
                    String sql11 = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`first_visit_date`," +
                            "`age_range`,`reservations_id`," +
                            "`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`,  " +
                            "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                            " `customer_sex`, `customer_age`,  " +
                            " `qq_number`, `wechat_number`, `other_contact`, `doctor`,`country`," +
                            " `province`, `cities`, `region`,`address`," +
                            " `archiving`, `entry_clerk` ,`update_people`," +
                            "  `filing_time`," +
                            " `customer_phone`,`remarks`,`start_time`,`end_time`,create_appointment_time,occupation,yellow_number)  " +
                            " select '" + id + "',first_visit_date," +
                            "  age_range,id," +
                            " '" + ShiroKit.getUser().getOutpatientName() + "',phone_shar_ship,'未开单','" + customerName + "' ," +
                            "'" + mediumname3 + "','" + mediumname2 + "','" + selectReasons + "', one_channel,two_channel,thr_channel," +
                            " '" + sex + "', '" + age + "', " +
                            " qq_number,wechat_number,other_contact,'未指定医生',country," +
                            " '" + provincei + "', '" + citiesi + "','" + regioni + "','" + address + "'," +
                            " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "', '" + DateTimeKit.now() + "'," +
                            " '" + customerPhone + "'," +
                            " remarks ,'" + customerPublicService.getStartTime() + "','" + customerPublicService.getEndTime() + "','" + DateTimeKit.now() + "','" + occupation + "','" + yellowNumbers + "'" +
                            " from reservations_info" +
                            " where customer_phone='" + customerPhone + "' limit 0,1";
                    return sqlMapper.insert(sql11);
                }
            } else {
                String sql2 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone='" + customerPhone + "' limit 0,1";
                CustomerInfo info = sqlMapper.selectOne(sql2, CustomerInfo.class);
                if (info != null) {
                    String id = CommUtils.getUUID();
                    String sql3 = "select id from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone='" + customerPhone + "' and " +
                            "left(create_appointment_time,10) ='" + customerPublicService.getStartTime().substring(0, 10) + "'";
                    List<CustomerInfo> cinfo2 = sqlMapper.selectList(sql3, CustomerInfo.class);
                    if (cinfo2.size() > 0) {
                        String sqlupd2 = "update " + ShiroKit.getUser().getCustomer_info() + "  set  " +
                                "start_time='" + customerPublicService.getStartTime() + "',end_time='" + customerPublicService.getEndTime() + "'," +
                                "archiving='" + ShiroKit.getUser().getAccount() + "'," +
                                "create_appointment_time = '" + DateTimeKit.now() + "'," +
                                "customer_name= '" + customerName + "'," +
                                "customer_age= '" + age + "'," +
                                "customer_sex= '" + sex + "'," +
                                "occupation= '" + occupation + "'," +
                                "address= '" + address + "'," +
                                "province= '" + provincei + "'," +
                                "cities= '" + citiesi + "'," +
                                "region= '" + regioni + "'," +
                                "medical_reasons= '" + medicalReasons + "'," +
                                "one_medium= '" + mediumname3 + "'," +
                                "two_medium= '" + mediumname2 + "'," +
                                "thr_medium= '" + selectReasons + "' " +
                                " where customer_phone='" + customerPhone + "'" +
                                " and left(start_time,10)='" + customerPublicService.getStartTime().substring(0, 10) + "'";
                        return sqlMapper.update(sqlupd2);
                    } else {
                        String sql22 = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`first_visit_date`,`actual_account_balance`," +
                                "`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`," +
                                "`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`, `pseudonym`,   " +
                                "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                                " `customer_sex`, `customer_age`, `birthday`,  `address`, `referee`, `referee_ship`, `id_card_no`," +
                                " `fixed_telephone`, `is_have_children`, `email`, `zip_code`, " +
                                "  `number_of_audits`, `auditor_time`, `final_auditor`," +
                                "  `non_transaction_level`, `transaction_level`, `characters`, " +
                                "`consumption_habits`, `is_return_visit`, `cause_of_no_return_visit`, `consum_ability`," +
                                " `qq_number`, `wechat_number`, `other_contact`,`doctor`, `country`," +
                                " `province`, `cities`, `region`, `medical_record_number`, " +
                                " `marital_status`, `occupation`, `archiving`, `entry_clerk` ,`update_people`," +
                                "  `filing_time`,`customer_phone`,`remarks`,`start_time`,`end_time`," +
                                "create_appointment_time,medical_reasons,yellow_number)  " +
                                " select '" + id + "',first_visit_date,actual_account_balance," +
                                " give_account_balance,account_arrears, age_range,reservations_id," +
                                " arrival_store,phone_shar_ship,'未开单','" + customerName + "' , pseudonym,  " +
                                "'" + mediumname3 + "','" + mediumname2 + "','" + selectReasons + "', one_channel,two_channel,thr_channel," +
                                " '" + sex + "', '" + age + "', birthday, '" + address + "', referee, referee_ship, id_card_no," +
                                " fixed_telephone, is_have_children, email, zip_code," +
                                "   number_of_audits, auditor_time, final_auditor," +
                                " non_transaction_level,transaction_level,characters," +
                                " consumption_habits,is_return_visit,cause_of_no_return_visit,consum_ability," +
                                " qq_number,wechat_number,other_contact,'未指定医生',country," +
                                " '" + provincei + "', '" + citiesi + "','" + regioni + "',medical_record_number,marital_status," +
                                " '" + occupation + "',archiving,entry_clerk,update_people, '" + DateTimeKit.now() + "'," +
                                " '" + customerPhone + "',remarks ,'" + customerPublicService.getStartTime() + "','" + customerPublicService.getEndTime() + "','" +
                                DateTimeKit.now() + "','" + medicalReasons + "','" + yellowNumbers + "' from " + ShiroKit.getUser().getCustomer_info()
                                + " where customer_phone='" + customerPhone + "' limit 0,1";
                        return sqlMapper.insert(sql22);
                    }
                } else {
                    return 1;
                }
            }
        }
    }

    /**
     * 跳转医生个人预约
     */
    @RequestMapping("/customer_information")
    public String customer_information(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "customer_information.html";
    }

    /**
     * 跳转 到店 预约视图 只显示未指定医生
     */
    @RequestMapping("/customer_reservationViewsDoctor")
    public String customer_reservationViewsDoctor(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        model.addAttribute("registerIsRing", ShiroKit.getUser().getRegisterIsRing());
        return PREFIX + "customer_reservationViewsDoctor.html";
    }

    /**
     * 跳转 到店 预约视图
     */
    @RequestMapping("/customer_reservationViews")
    public String customer_reservationViews(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        model.addAttribute("registerIsRing", ShiroKit.getUser().getRegisterIsRing());
        return PREFIX + "customer_reservationViews.html";
    }

    /**
     * 跳转 TC 预约视图
     */
    @RequestMapping("/customer_reservationViewsOne")
    public String customer_reservationViewsOne(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        return PREFIX + "customer_reservationViewsOne.html";
    }

    /**
     * 跳转 医生 预约视图
     */
    @RequestMapping("/customer_reservationViewsTwo")
    public String customer_reservationViewsTwo(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        return PREFIX + "customer_reservationViewsTwo.html";
    }

    /**
     * 跳转 市场 预约视图
     */
    @RequestMapping("/customer_reservationViewsThr")
    public String customer_reservationViewsThr(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", ShiroKit.getUser().getId());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIX + "customer_reservationViewsThr.html";
    }

    /**
     * 跳转信息录入
     */
    @RequestMapping("/customer_doctorWeek/{ids}")
    public String customer_doctorWeek(@PathVariable String ids, Model model) {
        String id = ids.split(",")[0];
        String time = ids.split(",")[1];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql1 = " select t.doctor_id as doctorId ,t1.account as doctorName ,t.the_date as theDate" +
                " from doctor_scheduling t  left join user t1 on t.doctor_id=t1.id " +
                " where t.doctor_id='" + id + "' and t.status=2 " +
                " and t.the_date between '" + time + "'-INTERVAL WEEKDAY('" + time + "') DAY and '" + time + "'+ INTERVAL 6-WEEKDAY('" + time + "') DAY ";
        List<DoctorSchedulingInfo> schedulingInfo = sqlMapper.selectList(sql1, DoctorSchedulingInfo.class);
        String sql = "select * from user where id ='" + id + "'";
        User user = sqlMapper.selectOne(sql, User.class);
        model.addAttribute("id", id);
        model.addAttribute("time", time);
        model.addAttribute("doctorName", user.getAccount());
        model.addAttribute("schedulingInfo", schedulingInfo);
        return PREFIX + "customer_doctorWeek.html";
    }

    @RequestMapping(value = "/to_openByReservationId/{reservationId}/{tabId}")
    public String to_openByReservationId(@PathVariable String reservationId, @PathVariable String tabId, Model model) throws Exception {
        CustomerInfo customerInfo = customerDetailsService.selectOneByReservationsId(reservationId);
        FirstCustomerInfo firstCustomerInfo = customerDetailsService.firstVisitInformation(reservationId); //首次到店的患者信息
        customerDetailsService.getCustomerInformationsList();
        customerInfo.setFirstAppointmentPayService(firstCustomerInfo.getAppointmentPayService());
        customerInfo.setFirstArchiving(firstCustomerInfo.getArchiving());
        customerInfo.setFirstArrivalTime(firstCustomerInfo.getArrivalTime());
        customerInfo.setFirstFieldTc(firstCustomerInfo.getFieldTc());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("tabId", tabId);
        model.addAttribute("id", customerInfo.getId());
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("auditswitch", ShiroKit.getUser().getAuditswitch());
        model.addAttribute("roleNameLogin", ShiroKit.getUser().getRoleName());
        model.addAttribute("dealyesLogin", ShiroKit.getUser().getDealyes());
        return PREFIY + "customer_Details.html";
    }

    @RequestMapping(value = "/to_openByReservationIdtest/{reservationId}/{tabId}")
    public String to_openByReservationIdtest(@PathVariable String reservationId, @PathVariable String tabId, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(reservationId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableName = tableHead + "recharge_info";
        CustomerInfo customerInfo = service.selectOneByReservationsId(reservationId);
        String sqlresrvations = "select id from reservations_info where id='" + customerInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        if (reservationsInfo == null) {
            String sqlcu = "select * from " + ShiroKit.getUser().getCustomer_info() + "  where id='" + customerInfo.getId() + "'";
            CustomerInfo customer = sqlMapper.selectOne(sqlcu, CustomerInfo.class);
            reservationsService.insert(customer);
        }
        //看诊详情
        List<ConsultantInfo> consultantInfoList = consultantService.getConsultantInfoList2(customerInfo.getReservationsId());
        for (ConsultantInfo info1 : consultantInfoList) {
            if (info1.getDiagnosisTime() != "" && info1.getDiagnosisTime() != null) {
                info1.setDiagnosisTimeOne(info1.getDiagnosisTime().substring(0, 10));
                info1.setDiagnosisTimeTwo(info1.getDiagnosisTime().substring(11, info1.getDiagnosisTime().length()));
            }
        }
        //成交记录
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime," +
                "sum(t1.service_actual_pay)+sum(t1.deposit_amount) as totleServiceActualPay," +
                "(select sum(folding_pay) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) as totleFoldingPay," +
                "(select sum(deduction_amount) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) as totaldeductionAmount," +
                "sum(t1.arrears) as totleArrears,group_concat(distinct t1.remarks) as remarks," +
                " t1.folding_pay as foldingPay,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "group_concat(distinct t2.pay_service_name) as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "left(t1.get_time,19) as getTime ," +
                " group_concat(distinct t1.doctor) as doctor,t1.orthodontic_number as orthodonticNumber " +
                " from " + tableName1 + " t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and pay_service_id is not null and t1.deal_status='已结账' group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        //未结账记录
        String sqlno = "SELECT t1.id AS id,t1.customer_id AS customerId,t1.reservations_id AS reservationsId,t1.outpatient_name AS outpatientName," +
                " t1.deal_status AS dealStatus, left(t1.get_time,19) as getTime,t1.operation_time as operationTime, sum(t1.service_actual_pay) as serviceActualPay, " +
                " GROUP_CONCAT(DISTINCT t1.remarks) AS remarks,GROUP_CONCAT(DISTINCT t1.doctor) AS doctor" +
                " FROM " + tableName1 + " t1 LEFT JOIN " + ShiroKit.getUser().getPay_service_info() + " t2 ON t1.pay_service_id=t2.id" +
                " WHERE t1.reservations_id='" + customerInfo.getReservationsId() + "'  AND (t1.deal_status='已开单' or t1.deal_status='待审核')" +
                " group by t1.get_time order by t1.get_time desc ";
        List<PayServicedInfo> NoPayServiceInfoList = sqlMapper.selectList(sqlno, PayServicedInfo.class);
        String getTime = "";
        for (PayServicedInfo info : payServiceInfoList) {
            if (info != null) {
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                getTime = info.getGetTime();
            }
            if (StringUtil.isNotEmpty(info.getOrthodonticNumber())) {
                customerInfo.setOrthodonticNumber(info.getOrthodonticNumber());
            }
        }
        //到过的店
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsInfo.getId() + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        String customerTables = "";
        String customerTablesd = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' ";
                rechargeTables += "select document_number,deal_id,id2,recharge_people,operation_time,remarks from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' " +
                        "and arrival_time is not null ";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                rechargeTables += "select document_number,deal_id,id2,recharge_people,operation_time,remarks from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' union ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' " +
                        "and arrival_time is not null  union ";
            }
        }
        FirstCustomerInfo customerInfoFirst = service.selectOneByReservationsIdFirst(reservationId, customerTablesd);  //首次到店患者信息
        //就诊记录
        String sql11 = "select * from (" + customerTables + ") t order by t.startTime desc";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql11, CustomerInfo.class);
        for (CustomerInfo infos : customerInfoList) {
            infos.setOutpatientName(ShiroKit.getUser().getOutpatientName());
            if (infos.getStartTime() != "" && infos.getStartTime() != null) {
                infos.setStartTimeOne(infos.getStartTime().substring(0, 10));
                infos.setStartTimeTwo(infos.getStartTime().substring(11, infos.getStartTime().length()));
            }
        }
        //账单记录
        Double totalServiceActualPay = 0.00;
        Double totalArrears = 0.00;
        String custDealSql = "select t1.id2 as id2," +
                "t1.reservations_id as reservationsId, " +
                "t1.outpatient_name as outpatientName," +
                "left(t1.operation_time,19) as operationTime," +
                "t1.deal_status as dealStatus," +
                "GROUP_CONCAT( distinct (t1.doctor)) as doctor,GROUP_CONCAT( distinct (t1.nurse)) as nurse," +
                "t1.tc_name as tcName," +
                "sum(t1.service_actual_pay+t1.arrears+t1.deduction_amount+t1.deposit_amount) AS foldingPay," +
                "sum(t1.service_actual_pay) as serviceActualPay," +
                "sum(t1.arrears) as arrears," +
                "sum(t1.deduction_amount) as deductionAmount," +
                "sum(t1.deposit_amount) as depositAmount," +
                "t1.remarks as  remarks,(select distinct(r1.document_number) from (" + rechargeTables + ") r1 where r1.deal_id=t1.id group by r1.deal_id) as documentNumber " +
                "from (" + dealTables + ") t1 where t1.deal_status='已结账' and t1.reservations_id = '" + reservationId + "' " +
                "group by t1.operation_time order by t1.operation_time desc";
        List<PayServicedInfo> custDealList = sqlMapper.selectList(custDealSql, PayServicedInfo.class);
        for (int i = 0; i < custDealList.size(); i++) {
            List<PayServicedInfo> dealList = getDealInfoList(custDealList.get(i).getOperationTime(), custDealList.get(i).getReservationsId());
            custDealList.get(i).setDealList(dealList);
            custDealList.get(i).setDocumentNumber(dealList.get(0).getDocumentNumber());
            totalServiceActualPay = totalServiceActualPay + custDealList.get(i).getServiceActualPay();
            totalArrears = totalArrears + custDealList.get(i).getArrears();
        }
        //支付记录
        String payDealSql = "select t.outpatient_name as outpatientName,left(t.get_time,19) as getTime,t.is_do as isDo,t.tc_name as tcName,t.deal_status as dealStatus,t2.recharge_people " +
                "as rechargePeople,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay) as serviceActualPay, sum(t.arrears) as arrears," +
                "(sum(t.folding_pay)+sum(t.arrears)) as tkfoldingPay,sum(t.deduction_amount) AS deductionAmount,sum(t.deposit_amount) as depositAmount," +   //退款=应收+欠费
                "t2.remarks as remarks from (" + dealTables + ") t left join (select b.id2 as id2, b.recharge_people as recharge_people, " +
                "b.operation_time as operation_time,b.remarks as remarks from (" + rechargeTables + ") b group by b.operation_time) t2 on t.get_time = t2.operation_time where " +
                "t.reservations_id='" + customerInfo.getReservationsId() + "' and t.deal_status = '已结账' group by t.get_time order by t.get_time desc;";
        List<PayServicedInfo> payDealList = sqlMapper.selectList(payDealSql, PayServicedInfo.class);
        Double totalPayDealActualPay = 0.00;
        Double totalPayDealArrears = 0.00;
        for (int i = 0; i < payDealList.size(); i++) {
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getServiceActualPay())).doubleValue();
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getDepositAmount())).doubleValue();

            totalPayDealArrears = BigDecimal.valueOf(totalPayDealArrears).add(BigDecimal.valueOf(payDealList.get(i).getArrears())).doubleValue();
        }
        //欠费记录
        String arrearsDealSql = "select * from (select t.id2 as id2,t.reservations_id as reservationsId,t.customer_id as customerId," +
                "t.deal_status as dealStatus,t.outpatient_name as outpatientName,t.remarks as remarks,left(t.operation_time,19) as operationTime," +
                "t.doctor as doctor,t.tc_name as tcName,t.nurse as nurse,sum(t.deposit_amount) AS depositAmount,sum(t.deduction_amount) AS deductionAmount,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay)+sum(t.deposit_amount) as serviceActualPay,sum(t.arrears) as arrears,group_concat(distinct t1.pay_service_name) as payServiceName " +
                "from (" + dealTables + ") t  left join " + ShiroKit.getUser().getPay_service_info() + " t1 on t.pay_service_id=t1.id where t.deal_status='已结账' group by t.operation_time ) t1 where t1.reservationsId = '" + customerInfo.getReservationsId() + "' and t1.arrears  >0 order by t1.operationTime desc;";
        List<PayServicedInfo> arrearsDealList = sqlMapper.selectList(arrearsDealSql, PayServicedInfo.class);
        Double totalArrearsAmount = 0.00;
        for (int i = 0; i < arrearsDealList.size(); i++) {
            totalArrearsAmount += arrearsDealList.get(i).getArrears();
        }
        //通过预约ID  执行记录
        String sqll = "select t1.id as id,t1.id2 as id2,t1.customer_id as customerId,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,left(t3.recharge_time,19) as rechargeTime,t1.remarks as remarks," +
                " t1.arrears as arrears,t2.pay_service_name as payServiceName,t1.get_time as getTime from (" + dealTables + ") t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id left join " + tableName + " t3 on t3.id2=t1.id2 " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and  t1.deal_status ='已结账'  group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList1 = sqlMapper.selectList(sqll, PayServicedInfo.class);
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;   //
        Double totleServiceActualPay = 0.00; //总实收
        Double accountArrears = 0.00;  //总欠款
        for (PayServicedInfo info : payServiceInfoList1) {
            if (info != null) {
                if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                    if (info.getFoldingPay() != null) {
                        totleFoldingPay += info.getFoldingPay();
                    }
                    if (info.getServiceActualPay() != null) {
                        totleServiceActualPay += info.getServiceActualPay();//总实收
                    }
                    if (info.getArrears() != null) {
                        accountArrears += info.getArrears();//总欠款
                    }
                    info.setTotleReceivable(totleReceivable);
                    info.setTotleFoldingPay(totleFoldingPay);
                    info.setTotleServiceActualPay(totleServiceActualPay);
                    info.setAccountArrears(accountArrears);
                }
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                if (info.getRechargeTime() != "" && info.getRechargeTime() != null) {
                    info.setRechargeTimeOne(info.getRechargeTime().substring(0, 10));
                    info.setRechargeTimeTwo(info.getRechargeTime().substring(11, info.getRechargeTime().length()));
                }
            }
        }
        //病例记录
        //1、先查询当前客户的所有病例记录
        String caseInfoSql = "select left(t1.finnally_time,19) as finnallyTime1,t1.* from case_info t1  " +
                "where t1.reservations_id='" + customerInfo.getReservationsId() + "'order by t1.finnally_time desc";
        List<CaseInfo> caseInfoList = sqlMapper.selectList(caseInfoSql, CaseInfo.class);
        for (CaseInfo infos : caseInfoList) {
            if (infos != null) {
                if (infos.getOperationTime() != "" && infos.getOperationTime() != null) {
                    infos.setOperationTime(infos.getOperationTime().substring(0, 10));
                }
                String sql3 = "select id,pay_service_name as payServiceName from " + ShiroKit.getUser().getPay_service_info() + " where id ='" + infos.getPayServiceId() + "'";
                CaseInfo caseInfo1 = sqlMapper.selectOne(sql3, CaseInfo.class);
                if (caseInfo1 == null) {
                    continue;
                }
                infos.setPayServiceName(caseInfo1.getPayServiceName());
            }
        }
        //2.循环遍历每个病例记录，给对应病例的牙位属性赋值
        for (CaseInfo caseInfo : caseInfoList) {
            String toothSIteSql = "select * from tooth_site t1 where t1.case_id='" + caseInfo.getId() + "' ";//然后查询牙位集合
            List<ToothSite> toothSiteList = sqlMapper.selectList(toothSIteSql, ToothSite.class);
            for (ToothSite toothSite : toothSiteList) {//根据对应的牙位类型，给病例实体的对应牙位属性赋值
                if ("1".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite1List().add(toothSite);
                }
                if ("2".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite2List().add(toothSite);
                }
                if ("3".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite3List().add(toothSite);
                }
                if ("4".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite4List().add(toothSite);
                }
                if ("5".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite5List().add(toothSite);
                }
            }
        }
        String selectsql = "select id from today_operation_info where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "'";
        List<DoctorOperationInfo> doctorOperationInfo = sqlMapper.selectList(selectsql, DoctorOperationInfo.class);
        if (doctorOperationInfo.size() == 0) { //是否操作过该患者
            String insertSql = " INSERT INTO today_operation_info  (customer_id,reservations_id,szm,operation_people,customer_name, " +
                    " customer_sex,customer_age, customer_phone,store,operation_time) values  " +
                    " ('" + customerInfo.getId() + "','" + customerInfo.getReservationsId() + "','" + customerInfo.getSzm() + "','" + ShiroKit.getUser().getAccount() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerSex() + "', " +
                    " '" + customerInfo.getCustomerAge() + "','" + customerInfo.getCustomerPhone() + "','" + customerInfo.getArrivalStore() + "','" + DateTimeKit.now() + "') ";
            sqlMapper.insert(insertSql);//插入 今日操作数据 前台
        } else {
            String updatesql = "update today_operation_info set operation_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                    " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "'";
            sqlMapper.update(updatesql);
        }
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')"; //获取抵扣方式
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        String jfbalancesql = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(jfbalancesql, ScoreDealInfo.class);
        BigDecimal b1 = new BigDecimal(Double.parseDouble(ShiroKit.getUser().getProportional()));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
        Double jfbalance = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String selsql = "select reservations_id,members_num from members_user where reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        if (membersUser != null) {
            customerInfo.setMembersNum(membersUser.getMembersNum());
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("checkoutMethodHtml", checkoutMethodHtml);
        model.addAttribute("custDealList", custDealList);
        model.addAttribute("payDealList", payDealList);
        model.addAttribute("arrearsDealList", arrearsDealList);
        model.addAttribute("totalServiceActualPay", totalServiceActualPay);
        model.addAttribute("totalArrears", totalArrears);
        model.addAttribute("totalPayDealActualPay", totalPayDealActualPay);
        model.addAttribute("totalPayDealArrears", totalPayDealArrears);
        model.addAttribute("totalArrearsAmount", totalArrearsAmount);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("roleName", ShiroKit.getUser().getRoleNames());
        model.addAttribute("roleNameLogin", ShiroKit.getUser().getRoleName());
        model.addAttribute("dealyesLogin", ShiroKit.getUser().getDealyes());
        model.addAttribute("payServiceInfoList", payServiceInfoList); //结账记录
        model.addAttribute("payServiceInfoList1", payServiceInfoList1); //结账记录
        model.addAttribute("NoPayServiceInfoList", NoPayServiceInfoList); //未结账记录
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        model.addAttribute("customerId", customerInfo.getId());
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("customerInfo1", customerInfo);
        model.addAttribute("customerInfoFirst", customerInfoFirst);  //首次到店患者信息
        model.addAttribute("getTime", getTime);
        model.addAttribute("tabId", tabId);
        model.addAttribute("consultantInfo", customerInfo);
        model.addAttribute("caseInfoList", caseInfoList);
        model.addAttribute("consultantInfoList", consultantInfoList); //看诊记录
        model.addAttribute("customerInfoList", customerInfoList);//就诊记录
        model.addAttribute("auditswitch", ShiroKit.getUser().getAuditswitch());
        model.addAttribute("jfbalance", jfbalance);
        String jfbalancesql1 = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo1 = sqlMapper.selectOne(jfbalancesql1, ScoreDealInfo.class);
        model.addAttribute("jfbalancea", scoreDealInfo1.getScoreBalance());
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        String getOrthodonticsMoney = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_orthodontics_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(getOrthodonticsMoney, MembersUser.class);
        model.addAttribute("orthodonticsMoney", membersUser2.getMoneyBalance());
        model.addAttribute("khmoneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("khjfbalance", jfbalance);
        model.addAttribute("arrivalTimeStr", customerInfo.getArrivalTime());
        model.addAttribute("treatmentUnit", customerInfo.getTreatmentUnit());
        model.addAttribute("isRefundAdmin", ShiroKit.getUser().getIsRefundAdmin());
        String vipLevelName = memberProductService.getVipLevelName(customerInfo.getReservationsId());
        model.addAttribute("vipLevelName", vipLevelName);
        String updasql = "update members_user set vip_level_name='" + vipLevelName + "' where reservations_id='" + customerInfo.getReservationsId() + "'";
        sqlMapper.update(updasql);
        return PREFIY + "customer_customerDetails.html";
    }

    @RequestMapping(value = "/to_openByCustomerId/{id}")
    public String to_openByCustomerId(@PathVariable String id, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        CustomerInfo customerInfo1 = service.selectOneById(id);   //当前记录的患者信息
        CustomerInfo customerInfo = service.selectOneByReservationsId(customerInfo1.getReservationsId());
        String sqlresrvations = "select id from reservations_info where id='" + customerInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        if (reservationsInfo == null) {
            reservationsService.insert(customerInfo);
        }
        //看诊详情
        List<ConsultantInfo> consultantInfoList = consultantService.getConsultantInfoList2(customerInfo.getReservationsId());
        for (ConsultantInfo info1 : consultantInfoList) {
            if (info1.getDiagnosisTime() != "" && info1.getDiagnosisTime() != null) {
                info1.setDiagnosisTimeOne(info1.getDiagnosisTime().substring(0, 10));
                info1.setDiagnosisTimeTwo(info1.getDiagnosisTime().substring(11, info1.getDiagnosisTime().length()));
            }
        }
        //成交记录
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime," +
                "sum(t1.service_actual_pay)+sum(t1.deposit_amount) as totleServiceActualPay," +
                "(select sum(folding_pay) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) as totleFoldingPay," +
                "(select sum(deduction_amount) from " + tableName1 + " a where a.operation_time=t1.operation_time and a.operation_time=a.get_time) as totaldeductionAmount," +
                "sum(t1.arrears) as totleArrears,group_concat(distinct t1.remarks) as remarks," +
                " t1.folding_pay as foldingPay,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "group_concat(distinct t2.pay_service_name) as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "left(t1.get_time,19) as getTime ," +
                " group_concat(distinct t1.doctor) as doctor,t1.orthodontic_number as orthodonticNumber " +
                " from " + tableName1 + " t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and pay_service_id is not null and t1.deal_status='已结账' group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        //未结账记录
        String sqlno = "SELECT t1.id AS id,t1.customer_id AS customerId,t1.reservations_id AS reservationsId,t1.outpatient_name AS outpatientName," +
                " t1.deal_status AS dealStatus, left(t1.get_time,19) as getTime,t1.operation_time as operationTime, sum(t1.service_actual_pay) as serviceActualPay, " +
                " GROUP_CONCAT(DISTINCT t1.remarks) AS remarks,GROUP_CONCAT(DISTINCT t1.doctor) AS doctor" +
                " FROM " + tableName1 + " t1 LEFT JOIN " + ShiroKit.getUser().getPay_service_info() + " t2 ON t1.pay_service_id=t2.id" +
                " WHERE t1.reservations_id='" + customerInfo.getReservationsId() + "' AND (t1.deal_status='已开单' or t1.deal_status='待审核')" +
                " group by t1.get_time order by t1.get_time desc ";
        List<PayServicedInfo> NoPayServiceInfoList = sqlMapper.selectList(sqlno, PayServicedInfo.class);
        String getTime = "";
        for (PayServicedInfo info : payServiceInfoList) {
            if (info != null) {
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                getTime = info.getGetTime();
            }
            if (StringUtil.isNotEmpty(info.getOrthodonticNumber())) {
                customerInfo.setOrthodonticNumber(info.getOrthodonticNumber());
            }
        }
        //到过的店
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsInfo.getId() + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        String customerTables = "";
        String customerTablesd = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' " +
                        "and arrival_time is not null ";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' union ";
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + customerInfo.getReservationsId() + "' " +
                        "and arrival_time is not null  union ";
            }
        }
        FirstCustomerInfo customerInfoFirst = service.selectOneByReservationsIdFirst(customerInfo1.getReservationsId(), customerTablesd);  //首次到店患者信息
        //就诊记录
        String sql11 = "select * from (" + customerTables + ") t order by t.startTime desc";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql11, CustomerInfo.class);
        for (CustomerInfo infos : customerInfoList) {
            infos.setOutpatientName(ShiroKit.getUser().getOutpatientName());
            if (infos.getStartTime() != "" && infos.getStartTime() != null) {
                infos.setStartTimeOne(infos.getStartTime().substring(0, 10));
                infos.setStartTimeTwo(infos.getStartTime().substring(11, infos.getStartTime().length()));
            }
        }
        //账单记录
        Double totalServiceActualPay = 0.00;
        Double totalArrears = 0.00;
        String custDealSql = "select t1.id2 as id2," +
                "t1.reservations_id as reservationsId, " +
                "t1.outpatient_name as outpatientName," +
                "left(t1.operation_time,19) as operationTime," +
                "t1.deal_status as dealStatus," +
                "GROUP_CONCAT( distinct (t1.doctor)) as doctor,GROUP_CONCAT( distinct (t1.nurse)) as nurse," +
                "t1.tc_name as tcName," +
                "sum(t1.service_actual_pay+t1.arrears+t1.deduction_amount+t1.deposit_amount) AS foldingPay," +
                "sum(t1.service_actual_pay) as serviceActualPay," +
                "sum(t1.arrears) as arrears," +
                "sum(t1.deduction_amount) as deductionAmount," +
                "sum(t1.deposit_amount) as depositAmount," +
                "t1.remarks as  remarks,(select distinct(r1.document_number) from (" + rechargeTables + ") r1 where r1.deal_id=t1.id group by r1.deal_id) as documentNumber " +
                "from (" + dealTables + ") t1 where t1.deal_status='已结账' and  t1.reservations_id = '" + customerInfo.getReservationsId() + "' " +
                "group by t1.operation_time order by t1.operation_time desc";
        List<PayServicedInfo> custDealList = sqlMapper.selectList(custDealSql, PayServicedInfo.class);
        for (int i = 0; i < custDealList.size(); i++) {
            List<PayServicedInfo> dealList = getDealInfoList(custDealList.get(i).getOperationTime(), custDealList.get(i).getReservationsId());
            custDealList.get(i).setDealList(dealList);
            custDealList.get(i).setDocumentNumber(dealList.get(0).getDocumentNumber());
            totalServiceActualPay = totalServiceActualPay + custDealList.get(i).getServiceActualPay() + custDealList.get(i).getDepositAmount();
            totalArrears = totalArrears + custDealList.get(i).getArrears();
        }
        //支付记录
        String payDealSql = "select t.outpatient_name as outpatientName,left(t.get_time,19) as getTime,t.is_do as isDo,t.tc_name as tcName,t.deal_status as dealStatus,t2.recharge_people " +
                "as rechargePeople,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay) as serviceActualPay,t2.remarks as remarks, sum(t.arrears) as arrears," +
                "(sum(t.folding_pay)+sum(t.arrears)) as tkfoldingPay,sum(t.deduction_amount) AS deductionAmount,sum(t.deposit_amount) as depositAmount " +   //退款=应收+欠费
                "from (" + dealTables + ") t left join (select b.id2 as id2, b.recharge_people as recharge_people, " +
                "b.operation_time as operation_time,b.remarks as remarks from (" + rechargeTables + ") b group by b.operation_time) t2 on t.get_time = t2.operation_time  where " +
                "t.reservations_id='" + customerInfo.getReservationsId() + "' and t.deal_status = '已结账' group by t.get_time order by t.get_time desc;";
        List<PayServicedInfo> payDealList = sqlMapper.selectList(payDealSql, PayServicedInfo.class);
        Double totalPayDealActualPay = 0.00;
        Double totalPayDealArrears = 0.00;
        for (int i = 0; i < payDealList.size(); i++) {
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getServiceActualPay())).doubleValue();
            totalPayDealActualPay = BigDecimal.valueOf(totalPayDealActualPay).add(BigDecimal.valueOf(payDealList.get(i).getDepositAmount())).doubleValue();

            totalPayDealArrears = BigDecimal.valueOf(totalPayDealArrears).add(BigDecimal.valueOf(payDealList.get(i).getArrears())).doubleValue();
        }
        //欠费记录
        String arrearsDealSql = "select * from (select t.id2 as id2,t.reservations_id as reservationsId,t.customer_id as customerId," +
                "t.deal_status as dealStatus,t.outpatient_name as outpatientName,t.remarks as remarks,left(t.operation_time,19) as operationTime," +
                "t.doctor as doctor,t.tc_name as tcName,t.nurse as nurse,sum(t.deposit_amount) AS depositAmount,sum(t.deduction_amount) AS deductionAmount,sum(t.folding_pay) as foldingPay,sum(t.service_actual_pay)+sum(t.deposit_amount) as serviceActualPay,sum(t.arrears) as arrears,group_concat(distinct t1.pay_service_name) as payServiceName " +
                "from (" + dealTables + ") t  left join " + ShiroKit.getUser().getPay_service_info() + " t1 on t.pay_service_id=t1.id where t.deal_status='已结账' group by t.operation_time ) t1 where t1.reservationsId = '" + customerInfo.getReservationsId() + "' and t1.arrears  >0 order by t1.operationTime desc;";
        List<PayServicedInfo> arrearsDealList = sqlMapper.selectList(arrearsDealSql, PayServicedInfo.class);
        Double totalArrearsAmount = 0.00;
        for (int i = 0; i < arrearsDealList.size(); i++) {
            totalArrearsAmount += arrearsDealList.get(i).getArrears();
        }
        String tableName = tableHead + "recharge_info";
        //通过预约ID  执行记录
        String sqll = "select t1.id as id,t1.id2 as id2,t1.customer_id as customerId,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,left(t3.recharge_time,19) as rechargeTime,t1.remarks as remarks," +
                " t1.arrears as arrears,t2.pay_service_name as payServiceName,t1.get_time as getTime from (" + dealTables + ") t1 left join " + ShiroKit.getUser().getPay_service_info() + " t2 on t1.pay_service_id=t2.id left join " + tableName + " t3 on t3.id2=t1.id2 " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and  t1.deal_status ='已结账'  group by  operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoList1 = sqlMapper.selectList(sqll, PayServicedInfo.class);
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;   //
        Double totleServiceActualPay = 0.00; //总实收
        Double accountArrears = 0.00;  //总欠款
        for (PayServicedInfo info : payServiceInfoList1) {
            if (info != null) {
                if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                    if (info.getFoldingPay() != null) {
                        totleFoldingPay += info.getFoldingPay();
                    }
                    //总实收
                    if (info.getServiceActualPay() != null) {
                        totleServiceActualPay += info.getServiceActualPay();
                    }
                    //总欠款
                    if (info.getArrears() != null) {
                        accountArrears += info.getArrears();
                    }
                    info.setTotleReceivable(totleReceivable);
                    info.setTotleFoldingPay(totleFoldingPay);
                    info.setTotleServiceActualPay(totleServiceActualPay);
                    info.setAccountArrears(accountArrears);
                }
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                if (info.getRechargeTime() != "" && info.getRechargeTime() != null) {
                    info.setRechargeTimeOne(info.getRechargeTime().substring(0, 10));
                    info.setRechargeTimeTwo(info.getRechargeTime().substring(11, info.getRechargeTime().length()));
                }
            }
        }
        //病例记录
        //1、先查询当前客户的所有病例记录
        String caseInfoSql = "select left(t1.finnally_time,19) as finnallyTime1,t1.* from case_info t1  " +
                "where t1.reservations_id='" + customerInfo.getReservationsId() + "'order by t1.finnally_time desc";
        List<CaseInfo> caseInfoList = sqlMapper.selectList(caseInfoSql, CaseInfo.class);
        for (CaseInfo infos : caseInfoList) {
            if (infos != null) {
                if (infos.getOperationTime() != "" && infos.getOperationTime() != null) {
                    infos.setOperationTime(infos.getOperationTime().substring(0, 10));
                }
                String sql3 = "select id,pay_service_name as payServiceName from " + ShiroKit.getUser().getPay_service_info() + " where id ='" + infos.getPayServiceId() + "'";
                CaseInfo caseInfo1 = sqlMapper.selectOne(sql3, CaseInfo.class);
                if (caseInfo1 == null) {
                    continue;
                }
                infos.setPayServiceName(caseInfo1.getPayServiceName());
            }
        }
        //2.循环遍历每个病例记录，给对应病例的牙位属性赋值
        for (CaseInfo caseInfo : caseInfoList) {//然后查询牙位集合
            String toothSIteSql = "select * from tooth_site t1 where t1.case_id='" + caseInfo.getId() + "' ";
            List<ToothSite> toothSiteList = sqlMapper.selectList(toothSIteSql, ToothSite.class);
            for (ToothSite toothSite : toothSiteList) { //根据对应的牙位类型，给病例实体的对应牙位属性赋值
                if (toothSite.getYaType().equals("1")) {
                    caseInfo.getToothSite1List().add(toothSite);
                }
                if (toothSite.getYaType().equals("2")) {
                    caseInfo.getToothSite2List().add(toothSite);
                }
                if (toothSite.getYaType().equals("3")) {
                    caseInfo.getToothSite3List().add(toothSite);
                }
                if (toothSite.getYaType().equals("4")) {
                    caseInfo.getToothSite4List().add(toothSite);
                }
                if (toothSite.getYaType().equals("5")) {
                    caseInfo.getToothSite5List().add(toothSite);
                }
            }
        }
        String selectsql = "select id from today_operation_info where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "' " +
                " and store='" + customerInfo.getArrivalStore() + "'";
        List<DoctorOperationInfo> doctorOperationInfo = sqlMapper.selectList(selectsql, DoctorOperationInfo.class);
        if (doctorOperationInfo.size() == 0) { //是否操作过该患者
            String insertSql = " INSERT INTO today_operation_info  (customer_id,reservations_id,szm,operation_people,customer_name, " +
                    " customer_sex,customer_age, customer_phone,store,operation_time) values  " +
                    " ('" + id + "','" + customerInfo.getReservationsId() + "','" + customerInfo.getSzm() + "','" + ShiroKit.getUser().getAccount() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerSex() + "', " +
                    " '" + customerInfo.getCustomerAge() + "','" + customerInfo.getCustomerPhone() + "','" + customerInfo.getArrivalStore() + "','" + DateTimeKit.now() + "') ";
            sqlMapper.insert(insertSql);//插入 今日操作数据 前台
        } else {
            String updatesql = "update today_operation_info set operation_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                    " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "' " +
                    " and store='" + customerInfo.getArrivalStore() + "'";
            sqlMapper.update(updatesql);
        }
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')";//获取抵扣方式
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        String jfbalancesql = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(jfbalancesql, ScoreDealInfo.class);
        BigDecimal b1 = new BigDecimal(Double.parseDouble(ShiroKit.getUser().getProportional()));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
        Double jfbalance = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String selsql = "select reservations_id,members_num from members_user where reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        if (membersUser != null) {
            customerInfo.setMembersNum(membersUser.getMembersNum());
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("checkoutMethodHtml", checkoutMethodHtml);
        model.addAttribute("custDealList", custDealList);  //账单记录
        model.addAttribute("payDealList", payDealList);
        model.addAttribute("arrearsDealList", arrearsDealList);
        model.addAttribute("totalServiceActualPay", totalServiceActualPay);
        model.addAttribute("totalArrears", totalArrears);
        model.addAttribute("totalPayDealActualPay", totalPayDealActualPay);
        model.addAttribute("totalPayDealArrears", totalPayDealArrears);
        model.addAttribute("totalArrearsAmount", totalArrearsAmount);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("roleName", ShiroKit.getUser().getRoleNames());
        model.addAttribute("roleNameLogin", ShiroKit.getUser().getRoleName());
        model.addAttribute("dealyesLogin", ShiroKit.getUser().getDealyes());
        model.addAttribute("payServiceInfoList", payServiceInfoList);
        model.addAttribute("NoPayServiceInfoList", NoPayServiceInfoList); //未结账记录
        model.addAttribute("payServiceInfoList1", payServiceInfoList1);   //执行记录
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        model.addAttribute("customerId", customerInfo1.getId());
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("customerInfoFirst", customerInfoFirst);  //首次到店患者信息
        model.addAttribute("getTime", getTime);
        model.addAttribute("caseInfoList", caseInfoList);
        model.addAttribute("consultantInfo", customerInfo);
        model.addAttribute("arrivalTimeStr", customerInfo1.getArrivalTime());
        model.addAttribute("customerInfo1", customerInfo1);
        model.addAttribute("consultantInfoList", consultantInfoList); //看诊记录
        model.addAttribute("customerInfoList", customerInfoList);//就诊记录
        model.addAttribute("auditswitch", ShiroKit.getUser().getAuditswitch());
        model.addAttribute("jfbalance", jfbalance);
        model.addAttribute("khjfbalance", jfbalance);
        String jfbalancesql1 = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal where reservations_id='" + customerInfo.getReservationsId() + "'";
        ScoreDealInfo scoreDealInfo1 = sqlMapper.selectOne(jfbalancesql1, ScoreDealInfo.class);
        model.addAttribute("jfbalancea", scoreDealInfo1.getScoreBalance());
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        model.addAttribute("moneyBalance", membersUser1.getMoneyBalance());
        String getOrthodonticsMoney = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_orthodontics_deal a " +
                " where a.reservations_id='" + customerInfo.getReservationsId() + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(getOrthodonticsMoney, MembersUser.class);
        model.addAttribute("orthodonticsMoney", membersUser2.getMoneyBalance());
        model.addAttribute("khmoneyBalance", membersUser1.getMoneyBalance());
        model.addAttribute("treatmentUnit", customerInfo1.getTreatmentUnit());
        model.addAttribute("isRefundAdmin", ShiroKit.getUser().getIsRefundAdmin());
        String vipLevelName = memberProductService.getVipLevelName(customerInfo.getReservationsId());
        model.addAttribute("vipLevelName", vipLevelName);
        String updasql = "update members_user set vip_level_name='" + vipLevelName + "' where reservations_id='" + customerInfo.getReservationsId() + "'";
        sqlMapper.update(updasql);
        return PREFIY + "customer_customerDetailss.html";
    }

    public List<PayServicedInfo> getDealInfoList(String operationTime, String reservationsId) throws Exception {
        if (ToolUtil.isEmpty(operationTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlresrvations = "select id from reservations_info where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsInfo.getId() + "' and status=1 ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' ";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsInfo.getId() + "' union ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsInfo.getId() + "' union ";
            }
        }
        String sql = "select t1.id as id,t1.outpatient_name as outpatientName,left(t1.get_time,19) as getTime,t1.is_do as isDo,t1.deal_status as dealStatus," +
                "t1.doctor1 as doctor,t1.nurse1 as nurse,t1.order_discount as orderDiscount,t1.deductionAmount as deductionAmount,t1.remarks as remarks,t1.serviceActualPay as serviceActualPay," +
                "t2.recharge_people as rechargePeople,t2.checkout_method as checkoutMethod," +
                "t2.document_number as documentNumber,t1.tc_name as tcName,left(t1.operation_time,19) as operationTime from (select t.id2 as id,t.outpatient_name as outpatient_name," +
                "t.get_time as get_time,t.tc_name as tc_name,t.is_do as is_do,t.deal_status as deal_status,GROUP_CONCAT(DISTINCT t.doctor) AS doctor1,GROUP_CONCAT(DISTINCT t.nurse) AS nurse1,(sum(t.service_actual_pay)+sum(t.deposit_amount)) as serviceActualPay," +
                "t.order_discount as order_discount,sum(t.deduction_amount) as deductionAmount,t.remarks as remarks,t.operation_time as operation_time from (" + dealTables + ") t where t.operation_time='" + operationTime + "' and t.reservations_id " +
                "= '" + reservationsId + "' and t.deal_status='已结账' group by t.get_time) t1 left join " + "(select b.recharge_people as recharge_people," +
                "b.document_number as  document_number,group_concat(distinct b.checkout_method) as checkout_method, b.operation_time as operation_time from (" + rechargeTables + ") b " +
                "group by b.operation_time) t2 on t1.get_time = t2.operation_time order by t1.get_time desc";
        List<PayServicedInfo> payServiceList = sqlMapper.selectList(sql, PayServicedInfo.class);
        return payServiceList;
    }

    /**
     * 批量修改TC
     */
    @RequestMapping(value = "/to_batchChoiceTc")
    public String to_batchChoiceTc(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        return PREFIY + "customer_batchchoiceTc.html";
    }

    //批量修改TC
    @RequestMapping(value = "/batchChoiceTc", method = RequestMethod.POST)
    @ResponseBody
    public int batchChoiceTc(String fieldTc, String tcName, String remarks, HttpServletRequest request) {
        String rek = "";
        if (StringUtil.isNotEmpty(remarks)) {
            rek = "；" + remarks + "";
        }
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " a set query_tc='" + tcName + "' ,remarks=concat(remarks,'" + rek + "') where field_tc='" + fieldTc + "'";
        sqlMapper.update(sql);
        String insql = "INSERT INTO `batch_choice_tc_log` (`updater`, `originaltc`, `nowtc`) VALUES " +
                "('" + ShiroKit.getUser().getName() + "','" + fieldTc + "', '" + tcName + "');";
        return sqlMapper.insert(insql);
    }

    /**
     * 查询客户信息
     */
    @RequestMapping(value = "/getCustomerByReach", method = RequestMethod.POST)
    @ResponseBody
    public StoreRecordsInfo getCustomerByReach(String reach, String pageStart, String pageSize, Model model) {
        String sql2 = " ";
        if (StringUtils.isNotBlank(reach)) {
            sql2 = "  and (t.customer_name like CONCAT('%','" + reach.trim() + "','%') or t.customer_phone like CONCAT('%','" + reach.trim() + "','%') " +
                    "  or t.customer_phone2 like CONCAT('%','" + reach.trim() + "','%') or " +
                    "  t.medical_record_number like CONCAT('%','" + reach.trim() + "','%')" +
                    " or t.szm like CONCAT('%','" + reach.trim() + "','%'))";
        }
        String sql = "select * from (select " +
                " ( " +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                " '男' " +
                " WHEN 2 THEN " +
                " '女' " +
                " ELSE " +
                " '未知' " +
                " END " +
                " ) as sex ,t.reservations_id as reservationsId,t.check_status as checkStatus, t.id,t.customer_name as customerName," +
                " t.customer_age as customerAge,t.customer_sex_head as customerSexHead," +
                " t.customer_phone as customerPhone,t.customer_phone2 as customerPhone2,t.arrival_store as arrivalStore,t.phone_shar_ship as phoneSharShip," +
                " t.account_arrears as accountArrears,t.medical_record_number as medicalRecordNumber," +
                " (select ifnull(sum(actual_account_balance),0) from reservemoney_orthodontics_deal t1  " +
                " where t.reservations_id=t1.reservations_id and (now() between t1.recharge_time and t1.end_time) limit 1) as orthodonticsStatus " +
                " from " + ShiroKit.getUser().getCustomer_info() + " t " +
                " where 1=1  " +
                "" + sql2 + " and arrival_status!=8 and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=9 and arrival_status!=10 " +
                " and arrival_time is not null order by arrival_time desc ) t2 group by t2.reservationsId" +
                " limit 0," + Integer.parseInt(pageStart) * Integer.parseInt(pageSize) + "";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql, CustomerInfo.class);
        String sql1 = "select count(1) from (select id from " + ShiroKit.getUser().getCustomer_info() + "  t where 1=1  " + sql2 + " group by reservations_id) t";
        Integer count = sqlMapper.selectOne(sql1, Integer.class);
        StoreRecordsInfo info = new StoreRecordsInfo();
        info.setCount(count);
        info.setCustomerInfoList(customerInfoList);
        return info;
    }

    /**
     * 查询客户信息
     */
    @RequestMapping(value = "/getCustomerByStore", method = RequestMethod.POST)
    @ResponseBody
    public List<CustomerInfo> getCustomerByStore(String reach, String pageStart, String pageSize, Model model) {
        String sql2 = " ";
        if (StringUtils.isNotBlank(reach)) {
            sql2 = "  and ( t.customer_name like CONCAT('%" + reach + "%') or  t.customer_phone like CONCAT('%" + reach + "%') or " +
                    "  t.medical_record_number like CONCAT('%" + reach + "%') or t.szm like CONCAT('%" + reach + "%')) ";
        }
        String sql = "select id,customerName, customerAge,customerPhone,reservationsId, sex,arrivalStore from (select t.id as id,t.customer_name as customerName,t.customer_age as customerAge," +
                "t.customer_phone as customerPhone, t.reservations_id as reservationsId, " +
                "  ( " +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                "    ) as sex,t.arrival_store as arrivalStore   from " + ShiroKit.getUser().getCustomer_info() + " t " +
                "where 1=1 " + sql2 + " and t.arrival_status not in (1,6,7,8,9,10) ) t1  group by reservationsId " +
                "limit 0," + Integer.parseInt(pageStart) * Integer.parseInt(pageSize);
        List<CustomerInfo> customerInfo = sqlMapper.selectList(sql, CustomerInfo.class);
        return customerInfo;
    }

    /**
     * 前台新建预约搜索
     */
    @RequestMapping(value = "/getCustomerByReachNew", method = RequestMethod.POST)
    @ResponseBody
    public StoreRecordsInfo getCustomerByReachNew(String reach, String pageStart, String pageSize, Model model) {
        String sql2 = " ";
        if (StringUtils.isNotBlank(reach)) {
            sql2 = "  and (t.customer_name like CONCAT('%','" + reach + "','%') or t.customer_phone like CONCAT('%','" + reach + "','%') " +
                    "  or t.customer_phone2 like CONCAT('%','" + reach + "','%') or " +
                    "  t.medical_record_number like CONCAT('%','" + reach + "','%')" +
                    " or t.szm like CONCAT('%','" + reach + "','%'))";
        }
        String sql = "select * from (select " +
                "(" +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                " '男' " +
                " WHEN 2 THEN " +
                " '女' " +
                " ELSE " +
                " '未知' " +
                " END " +
                " ) as sex ,t.reservations_id as reservationsId, t.id,t.customer_name as customerName,t.customer_age as customerAge,t.customer_sex_head as customerSexHead," +
                "t.customer_phone as customerPhone,t.customer_phone2 as customerPhone2,t.arrival_store as arrivalStore,t.phone_shar_ship as phoneSharShip," +
                " t.account_arrears as accountArrears,t.medical_record_number as medicalRecordNumber from " + ShiroKit.getUser().getCustomer_info() + " t " +
                " where 1=1 " + sql2 + " and arrival_status!=8 and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=9 and arrival_status!=10 " +
                " and arrival_time is not null order by arrival_time desc ) t2 group by t2.reservationsId" +
                " limit 0," + Integer.parseInt(pageStart) * Integer.parseInt(pageSize) + "";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql, CustomerInfo.class);
        String sql1 = "select count(1) from (select id from " + ShiroKit.getUser().getCustomer_info() + "  t where 1=1  " + sql2 + " group by reservations_id) t";
        Integer count = sqlMapper.selectOne(sql1, Integer.class);
        StoreRecordsInfo info = new StoreRecordsInfo();
        info.setScordd("dd");
        if (customerInfoList.size() == 0) {//本店查不到，查市场约的患者
            if (StringUtils.isNotBlank(reach)) {
                sql2 = "  and t.search_field like CONCAT('%','" + reach + "','%') ";
            }
            String sqlsc = "select * from (select " +
                    "       ( " +
                    "        CASE t.customer_sex " +
                    "        WHEN 1 THEN " +
                    "        '男' " +
                    "        WHEN 2 THEN " +
                    "        '女' " +
                    "        ELSE " +
                    "        '未知' " +
                    "        END " +
                    "        ) as sex , t.id as reservations_id,t.customer_name as customerName,t.one_channel as oneChannel," +
                    "t.department as department,t.customer_age as customerAge,t.customer_sex_head as customerSexHead,t.first_visit_date as firstVisitDate," +
                    "t.customer_phone as customerPhone,t.customer_phone2 as customerPhone2,t.status,t.arrival_store as arrivalStore," +
                    "t.phone_shar_ship as phoneSharShip from reservations_info t " +
                    " where 1=1 " + sql2 + " ) t2 group by t2.reservations_id order by t2.firstVisitDate " +
                    " limit 0," + Integer.parseInt(pageStart) * Integer.parseInt(pageSize) + "";
            customerInfoList = sqlMapper.selectList(sqlsc, CustomerInfo.class);
            String sql11 = "select count(1) from (select id from reservations_info t where 1=1 " + sql2 + " group by id) t";
            count = sqlMapper.selectOne(sql11, Integer.class);
            info.setScordd("sc");
        }
        info.setCount(count);
        info.setCustomerInfoList(customerInfoList);
        return info;
    }

    /**
     * 查询客户信息
     */
    @RequestMapping(value = "/getCustomerByReservationsId/{reservationsId}", method = RequestMethod.POST)
    @ResponseBody
    public CustomerInfo getCustomerByReservationsId(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select " +
                " (" +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                " ) as sex,t.* from " + ShiroKit.getUser().getCustomer_info() + " t " +
                " where t.reservations_id='" + reservationsId + "' and t.arrival_time is not null order by t.arrival_time limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    /**
     * 查询客户信息
     */
    @RequestMapping(value = "/getReservationsByReservationsId/{reservationsId}", method = RequestMethod.POST)
    @ResponseBody
    public CustomerInfo getReservationsByReservationsId(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select " +
                " ( " +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                " ) as sex,t.* from reservations_info t " +
                " where t.id='" + reservationsId + "' limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    /**
     * 前台修改保存预约
     */
    @RequestMapping(value = "/updateReservation", method = RequestMethod.POST)
    @ResponseBody
    public int updateReservation(String customerPhone, String projectData, String endTimeValue, String treatmentUnit,
                                 String fieldTc, String doctor, String remarks, String reservationsId,
                                 String startTimeValue, String customerId) throws Exception {
        String selsql = "select id,a.arrival_status,(case a.arrival_status when (1 or 9) then '预约' when 2 then '到店' when 3 then '就诊中'  " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话'  " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName,a.customer_name,a.customer_phone,a.customer_status," +
                "a.reservations_id from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selsql, CustomerInfo.class);
        //改变详情表状态
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + "  set appointment_pay_service= '" + projectData + "'," +
                " field_tc='" + fieldTc + "',query_tc='" + fieldTc + "',doctor='" + doctor + "',remarks_reservation='" + remarks
                + "',start_time='" + startTimeValue + "',end_time='" + endTimeValue + "',treatment_unit='" + treatmentUnit + "'," +
                " create_appointment_time = '" + DateTimeKit.now() + "'" +
                " where id='" + customerId + "'";
        //插入视图改动日志 修改预约
        String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','修改预约','" + ShiroKit.getUser().getId() + "','" + customerInfo.getCustomerStatus() + "', '"
                + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','预约项目：" + projectData + " </br>\n预约患者：" + customerInfo.getCustomerName() + " </br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                " </br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + "'," +
                " '" + customerId + "','" + customerInfo.getReservationsId() + "');";
        sqlMapper.insert(sq11);
        webSocket.sendMessageViews("修改预约", ShiroKit.getUser().getAbbreviation());
        return sqlMapper.update(sql);
    }

    /**
     * 通过 ID 查看患者信息是否成交
     */
    @RequestMapping(value = "/getCustomerIsDealStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public int getCustomerIsDealStatus(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id,isdeal_status,customer_status,deal_status  from " + ShiroKit.getUser().getCustomer_info() + " t" +
                " where t.id='" + id + "' ";
        String sql1 = "select id from " + ShiroKit.getUser().getRecharge_info() + " t where t.customer_id='" + id + "' limit 1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        CustomerInfo customerInfo1 = sqlMapper.selectOne(sql1, CustomerInfo.class);
        String sql2 = "select id from " + ShiroKit.getUser().getDeal_info() + " t where t.customer_id='" + id + "' limit 1";
        CustomerInfo customerInfo2 = sqlMapper.selectOne(sql2, CustomerInfo.class);
        if (customerInfo2 != null) {
            return 1;
        } else if ("新客首次".equals(customerInfo.getCustomerStatus())) {
            return 3;
        } else if (customerInfo1 != null) {  //充了储值或积分
            return 4;
        } else {
            return 2;
        }
    }

    /**
     * 复诊预约新加一条用户数据
     */
    @RequestMapping(value = "/addCustomerMarket", method = RequestMethod.POST)
    @ResponseBody
    public int addCustomerMarket(String customerPhone, String projectData, String duration, String treatmentUnit,
                                 String fieldTc, String doctor, String remarks, String reservationsId,
                                 String startTimeValue, String customerId) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = formatter.parse(startTimeValue);
        Date date1 = new Date(date.getTime() + Integer.parseInt(duration) * 60 * 1000);
        String endTimeValue = formatter.format(date1);
        Random rand = new Random();
        int randomNumber = rand.nextInt(9999);
        String customid = service.getId();
        String rsql = "select id,customer_name,customer_phone,archiving from reservations_info where id ='" + reservationsId + "'";
        ReservationsInfo rinfo = sqlMapper.selectOne(rsql, ReservationsInfo.class);
        String sqlc = "select * from " + ShiroKit.getUser().getCustomer_info() + " t where reservations_id ='" + reservationsId + "' " +
                "and t.arrival_status in (2,3,4,5) order by arrival_time desc limit 0,1 ";
        CustomerInfo cinfo = sqlMapper.selectOne(sqlc, CustomerInfo.class);
        if (cinfo != null) {  //市场复诊预约洁牙
            service.insertReturnfzjy(customid, projectData, treatmentUnit, customerPhone, fieldTc, ShiroKit.getUser().getCustomer_info(), cinfo.getId(), startTimeValue, endTimeValue, doctor, remarks);
        } else {
            String tableName = "";
            String sqld = "select id,abbreviation from distinction_customer_status where reservations_id ='" + reservationsId + "' and status=1  order by add_time desc limit 0,1 ";
            Dept infod = sqlMapper.selectOne(sqld, Dept.class);
            if (infod != null) {   //没来过本店，去过另一家店
                tableName = infod.getAbbreviation() + "customer_info";
                String sqld1 = "select id from " + tableName + " where reservations_id ='" + reservationsId + "' order by arrival_time desc limit 0,1 ";
                CustomerInfo infod1 = sqlMapper.selectOne(sqld1, CustomerInfo.class);
                service.insertReturnfzjy(customid, projectData, treatmentUnit, customerPhone, fieldTc, tableName, infod1.getId(), startTimeValue, endTimeValue, doctor, remarks);
            } else {
                String sql1 = "update reservations_info set identification_number='LS" + randomNumber + "' where id ='" + reservationsId + "'";
                sqlMapper.update(sql1);
                String sql = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`diagnosis_status`,`field_tc`,`query_tc`,`doctor`,`first_visit_date`," +
                        "`age_range`,`reservations_id`,`appointment_pay_service`," +
                        "`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`, medical_record_number, " +
                        "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                        " `customer_sex`, `customer_age`,customer_sex_head, scarchiving, " +
                        " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                        " `province`, `cities`, `region`,`address`," +
                        " `archiving`, `entry_clerk` ,`update_people`," +
                        "  `filing_time`,treatment_unit," +
                        " `customer_phone`,`remarks`,`start_time`,`end_time`,create_appointment_time,arrival_status,status)  " +
                        " select '" + customid + "','未看诊','" + fieldTc + "','" + fieldTc + "','" + doctor + "',first_visit_date," +
                        "  age_range,id,'" + projectData + "'," +
                        " '" + ShiroKit.getUser().getOutpatientName() + "',phone_shar_ship,'未开单',customer_name ,identification_number," +
                        "one_medium,two_medium,thr_medium, one_channel,two_channel,thr_channel," +
                        " customer_sex,customer_age,customer_sex_head,archiving, " +
                        " qq_number,wechat_number,other_contact,country,quarters," +
                        " province, cities,region," +
                        " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "', '" + DateTimeKit.now() + "'," +
                        " '" + treatmentUnit + "','" + customerPhone + "'," +
                        "'" + remarks + "','" + startTimeValue + "','" + endTimeValue + "','" + DateTimeKit.now() + "','9','预约' from reservations_info" +
                        " where id='" + reservationsId + "' limit 0,1";
                sqlMapper.insert(sql);
            }
        }
        //插入视图改动日志 市场预约洁牙
        String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新增预约','" + ShiroKit.getUser().getId() + "','预约', '"
                + rinfo.getCustomerName() + "', '" + rinfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','预约项目：" + projectData + " </br>\n预约患者：" + rinfo.getCustomerName() + " </br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                "</br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + "','" + customid + "'," +
                "'" + reservationsId + "');";
        sqlMapper.insert(sq11);
        webSocket.sendMessageViews("保存预约", ShiroKit.getUser().getAbbreviation());
        return 1;
    }

    /**
     * 复诊预约新加一条用户数据
     */
    @RequestMapping(value = "/addCustomerFz", method = RequestMethod.POST)
    @ResponseBody
    public int addCustomerFz(String customerPhone, String projectData, String duration, String treatmentUnit,
                             String fieldTc, String doctor, String remarks, String reservationsId,
                             String startTimeValue, String customerId) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = formatter.parse(startTimeValue);
        Date date1 = new Date(date.getTime() + Integer.parseInt(duration) * 60 * 1000);
        String endTimeValue = formatter.format(date1);
        String sql11 = " select id,max(cast(yellow_number as unsigned)) as yellowNumber from " + ShiroKit.getUser().getCustomer_info() + " ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql11, CustomerInfo.class);
        if ("洁牙,".equals(projectData)) {
            projectData = "洁牙";
        }
        //设置黄页编号
        String yellowNumbers = "0000123";
       /* if (customerInfo != null) {
            if (StringUtil.isNotEmpty(customerInfo.getYellowNumber()) && !"null".equals(customerInfo.getYellowNumber())) {
                yellowNumbers = Integer.parseInt(customerInfo.getYellowNumber()) + 1;
            }
        }*/
        String selsql = "select id,a.arrival_status,(case a.arrival_status when (1 or 9) then '预约' when 2 then '到店' when 3 then '就诊中'  " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话'  " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName," +
                "a.* from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "' and reservations_id='" + reservationsId + "'";
        CustomerInfo cinfo4 = sqlMapper.selectOne(selsql, CustomerInfo.class);
        String customid = service.getId();
        if (cinfo4 != null) {
            String sql = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`first_visit_date`,`actual_account_balance`," +
                    "`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`,`appointment_pay_service`," +
                    "`arrival_store`,`phone_shar_ship`,`deal_status`,status, `customer_name`, `pseudonym`,   " +
                    "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                    " `customer_sex`, `customer_age`, `birthday`,  `address`, `referee`, `referee_ship`, `id_card_no`," +
                    " `fixed_telephone`,`diagnosis_status`, `is_have_children`, `email`, `zip_code`, " +
                    "  `number_of_audits`, `auditor_time`, `final_auditor`," +
                    "  `non_transaction_level`, `transaction_level`, `characters`, " +
                    "`consumption_habits`, `is_return_visit`, `cause_of_no_return_visit`, `consum_ability`," +
                    " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                    " `province`, `cities`, `region`, `medical_record_number`, " +
                    " `marital_status`, `occupation`, `archiving`, `entry_clerk` ,`update_people`," +
                    "  `filing_time`," +
                    " `customer_phone`,customer_phone2,`field_tc`,`query_tc`,`doctor`,`remarks`,`remarks_reservation`,`start_time`,`end_time`,create_appointment_time," +
                    "yellow_number,scarchiving,treatment_unit,szm,update_time)  " +
                    " select '" + customid + "',first_visit_date,actual_account_balance," +
                    " give_account_balance,account_arrears, " +
                    "(case  " +
                    " WHEN (0<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<10) then '0-9' " +
                    " WHEN (10<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<20) then '10-19' " +
                    " WHEN (20<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<30) then '20-29' " +
                    " WHEN (30<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<40) then '30-39' " +
                    " WHEN (40<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<50) then '40-49' " +
                    " WHEN (50<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<60) then '50-59' " +
                    " WHEN (60<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<70) then '60-69' " +
                    " WHEN (70<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<80) then '70-79' " +
                    " WHEN (80<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<90) then '80-89' " +
                    " WHEN (90<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<100) then '90-99' " +
                    " else '99+' end), " +
                    " reservations_id,'" + projectData + "'," +
                    " arrival_store,phone_shar_ship,'未开单','预约',customer_name , pseudonym,  " +
                    "one_medium,two_medium,thr_medium, one_channel,two_channel,thr_channel," +
                    " customer_sex,customer_age, birthday, address, referee, referee_ship, id_card_no," +
                    " fixed_telephone,'未看诊', is_have_children, email, zip_code," +
                    "   number_of_audits, auditor_time, final_auditor," +
                    " non_transaction_level,transaction_level,characters," +
                    " consumption_habits,is_return_visit,cause_of_no_return_visit,consum_ability," +
                    " qq_number,wechat_number,other_contact,country," +
                    " province, cities,region,medical_record_number,marital_status," +
                    " occupation,'" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "', '" + DateTimeKit.now() + "'," +
                    " '" + customerPhone + "',customer_phone2,'" + fieldTc + "','" + fieldTc + "','" + doctor + "'," +
                    "remarks,'" + remarks + "','" + startTimeValue + "','" + endTimeValue + "','" + DateTimeKit.now() + "','" + yellowNumbers + "'" +
                    " ,scarchiving,'" + treatmentUnit + "',szm,'" + DateTimeKit.now() + "' from " + ShiroKit.getUser().getCustomer_info()
                    + " where reservations_id='" + reservationsId + "' order by arrival_time asc limit 0,1";
            int a = sqlMapper.insert(sql);
            String sql2 = "delete from " + ShiroKit.getUser().getCustomer_info() + " where reservations_id='" + reservationsId + "' and xcustomer_status='预约' and left(filing_time,10)=left(now(),10) ";
            sqlMapper.delete(sql2);
            //插入视图改动日志 复诊预约
            String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新增预约','" + ShiroKit.getUser().getId() + "','" + cinfo4.getCustomerStatus() + "', '"
                    + cinfo4.getCustomerName() + "', '" + cinfo4.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','预约项目：" + projectData + " </br>\n预约患者：" + cinfo4.getCustomerName() + " </br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                    "</br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + "'," +
                    "'" + customid + "','" + cinfo4.getReservationsId() + "');";
            sqlMapper.insert(sq11);
            webSocket.sendMessageViews("新增预约", ShiroKit.getUser().getAbbreviation());
            return a;
        } else {
            String sql = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,`diagnosis_status`,`field_tc`,`query_tc`,`doctor`,`first_visit_date`," +
                    "`age_range`,`reservations_id`,`appointment_pay_service`," +
                    "`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`,  " +
                    "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                    " `customer_sex`, `customer_age`, treatment_unit, " +
                    " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                    " `province`, `cities`, `region`,`address`," +
                    " `archiving`, `entry_clerk` ,`update_people`," +
                    "  `filing_time`," +
                    " `customer_phone`,customer_phone2,`remarks`,`remarks_reservation`,`start_time`,`end_time`,create_appointment_time,yellow_number)  " +
                    " select '" + customid + "','未看诊','" + fieldTc + "','" + fieldTc + "','" + doctor + "',first_visit_date," +
                    "(case  " +
                    " WHEN (0<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<10) then '0-9' " +
                    " WHEN (10<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<20) then '10-19' " +
                    " WHEN (20<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<30) then '20-29' " +
                    " WHEN (30<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<40) then '30-39' " +
                    " WHEN (40<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<50) then '40-49' " +
                    " WHEN (50<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<60) then '50-59' " +
                    " WHEN (60<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<70) then '60-69' " +
                    " WHEN (70<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<80) then '70-79' " +
                    " WHEN (80<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<90) then '80-89' " +
                    " WHEN (90<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<100) then '90-99' " +
                    " else '99+' end), " +
                    " id,'" + projectData + "'," +
                    " '" + ShiroKit.getUser().getOutpatientName() + "',phone_shar_ship,'未开单',customer_name ," +
                    "one_medium,two_medium,thr_medium, one_channel,two_channel,thr_channel," +
                    " customer_sex, (DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y')),'" + treatmentUnit + "'," +
                    " qq_number,wechat_number,other_contact,country," +
                    " province, cities,region,quarters," +
                    " '" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "', '" + DateTimeKit.now() + "'," +
                    " '" + customerPhone + "',customer_phone2," +
                    "remarks,'" + remarks + "','" + startTimeValue + "','" + endTimeValue + "','" + DateTimeKit.now() + "','" + yellowNumbers + "' from reservations_info" +
                    " where id='" + reservationsId + "' limit 0,1";
            //插入视图改动日志 复诊预约
            String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新增预约','" + ShiroKit.getUser().getId() + "','" + cinfo4.getCustomerStatus() + "', '"
                    + cinfo4.getCustomerName() + "', '" + cinfo4.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','预约项目：" + projectData + " </br>\n预约患者：" + cinfo4.getCustomerName() + " </br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                    "</br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + "','" + customid + "'," +
                    "'" + cinfo4.getReservationsId() + "');";
            sqlMapper.insert(sql);
            webSocket.sendMessageViews("新增预约", ShiroKit.getUser().getAbbreviation());
            return sqlMapper.insert(sq11);
        }
    }

    /**
     * 复诊新加一条用户数据  在预约  医生预约
     */
    @RequestMapping(value = "/addCustomerFzs", method = RequestMethod.POST)
    @ResponseBody
    public MembersArriveInfo addCustomerFzs(String customerPhone, String projectData, String treatmentUnit,
                                            String fieldTc, String doctor, String remarks, String reservationsId, String isFz,
                                            String startTimeValue, String duration, String customerId) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        //设置黄页编号
        String yellowNumbers = "0000123";
        String medicalRecordNumber = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = formatter.parse(startTimeValue);
        Date date1 = new Date(date.getTime() + Integer.parseInt(duration) * 60 * 1000);
        String endTimeValue = formatter.format(date1);
        MembersArriveInfo membersArriveInfos = new MembersArriveInfo();
        String selsql = "select id,a.arrival_status,(case a.arrival_status when (1 or 9) then '预约' when 2 then '到店' when 3 then '就诊中'  " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话'  " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName," +
                "a.* from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "' and reservations_id='" + reservationsId + "'";
        CustomerInfo customerIn = sqlMapper.selectOne(selsql, CustomerInfo.class);
        if (customerIn == null) {       // 去另外一家店复诊,查到去的哪家店
            yellowNumbers = customerPublicService.getMaxYellowNumber();
            String sqld = "select id,abbreviation from distinction_customer_status where reservations_id ='" + reservationsId + "' and status=1 order by add_time limit 0,1 ";
            Dept cinfo = sqlMapper.selectOne(sqld, Dept.class);
            String sql2 = " select id,reservations_id,customer_name,customer_phone,medical_record_number  as medicalRecordNumber " +
                    " from " + cinfo.getAbbreviation() + "customer_info t where reservations_id ='" + reservationsId + "' " +
                    " order by arrival_time desc limit 0,1 ";
            customerIn = sqlMapper.selectOne(sql2, CustomerInfo.class);
            medicalRecordNumber = customerIn.getMedicalRecordNumber(); //继承上一家的病历号
            customerIn.setAbbreviation(cinfo.getAbbreviation());
            //去另外一家店复诊，记录下
            String sql = "insert into distinction_customer_status (reservations_id,customer_name,customer_phone,arrival_store,abbreviation,deal_status,add_time,update_time,medical_record_number) " +
                    " values('" + customerIn.getReservationsId() + "','" + customerIn.getCustomerName() + "','" + customerIn.getCustomerPhone()
                    + "','" + ShiroKit.getUser().getOutpatientName() + "','" + ShiroKit.getUser().getAbbreviation() + "','未成交','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + medicalRecordNumber + "') ";
            sqlMapper.insert(sql);
        } else {
            medicalRecordNumber = customerIn.getMedicalRecordNumber();
            yellowNumbers = customerIn.getYellowNumber();
        }
        if (startTimeValue.compareTo((DateTimeKit.now())) < 0) {
            membersArriveInfos.setIds("11");
            return membersArriveInfos;
        } else {
            String tableName = tableHead + "customer_info";
            if (StringUtil.isNotEmpty(customerIn.getAbbreviation())) {
                tableName = customerIn.getAbbreviation() + "customer_info";
            }
            Double moneyBalance = 0.00;
            Double jfbalance = 0.00;
            String getMoneyBalance = "select sum(a.actual_account_balance) as moneyBalance from reservemoney_deal a " +
                    " where a.reservations_id='" + reservationsId + "' " +
                    " and a.add_store='" + ShiroKit.getUser().getOutpatientName() + "'";
            CustomerInfo customerInfo1 = sqlMapper.selectOne(getMoneyBalance, CustomerInfo.class);
            if (customerInfo1 != null) {
                moneyBalance = customerInfo1.getMoneyBalance();
            }
            String getjFBalance = "select sum(a.score_balance) as jfbalance from score_deal a " +
                    " where a.reservations_id='" + reservationsId + "' " +
                    " and a.add_store='" + ShiroKit.getUser().getOutpatientName() + "'";
            CustomerInfo customerInfo2 = sqlMapper.selectOne(getjFBalance, CustomerInfo.class);
            if (customerInfo2 != null) {
                jfbalance = customerInfo2.getJfbalance();
            }
            String id = service.getId();
            String sql = "INSERT INTO " + ShiroKit.getUser().getCustomer_info() + " (`id`,scarchiving,`diagnosis_status`,`first_visit_date`,`actual_account_balance`," +
                    "`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`,`appointment_pay_service`," +
                    "`arrival_store`,`phone_shar_ship`,`deal_status`, `status`,`customer_name`, `pseudonym`,szm, " +
                    "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                    " `customer_sex`,customer_sex_head, `customer_age`, `birthday`,  `address`, `referee`, `referee_ship`, `id_card_no`," +
                    " `fixed_telephone`, `is_have_children`, `email`, `zip_code`,treatment_unit, " +
                    "  `number_of_audits`, `auditor_time`, `final_auditor`,`yhbalance`,`jfbalance`,`money_balance`," +
                    "  `non_transaction_level`, `transaction_level`, `characters`, " +
                    "`consumption_habits`, `is_return_visit`, `cause_of_no_return_visit`, `consum_ability`," +
                    " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                    " `province`, `cities`, `region`, `medical_record_number`, " +
                    " `marital_status`, `occupation`, `archiving`, `entry_clerk` ,`update_people`," +
                    "  `filing_time`," +
                    " `customer_phone`,customer_phone2,`field_tc`,`query_tc`,`doctor`,`remarks`,`remarks_reservation`,`start_time`,`end_time`,create_appointment_time,yellow_number )  " +
                    " select '" + id + "',scarchiving,'未看诊',first_visit_date,actual_account_balance," +
                    " give_account_balance,account_arrears, " +
                    "(case " +
                    " WHEN (0<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<10) then '0-9' " +
                    " WHEN (10<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<20) then '10-19' " +
                    " WHEN (20<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<30) then '20-29' " +
                    " WHEN (30<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<40) then '30-39' " +
                    " WHEN (40<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<50) then '40-49' " +
                    " WHEN (50<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<60) then '50-59' " +
                    " WHEN (60<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<70) then '60-69' " +
                    " WHEN (70<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<80) then '70-79' " +
                    " WHEN (80<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<90) then '80-89' " +
                    " WHEN (90<=(DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y'))) and ((DATE_FORMAT(FROM_DAYS(TO_DAYS(arrival_time)-TO_DAYS(birthday)),'%Y'))<100) then '90-99' " +
                    " else '99+' end)," +
                    " reservations_id,'" + projectData + "'," +
                    " '" + ShiroKit.getUser().getOutpatientName() + "',phone_shar_ship,'未开单','预约',customer_name , pseudonym, szm, " +
                    "one_medium,two_medium,thr_medium, one_channel,two_channel,thr_channel," +
                    " customer_sex,customer_sex_head, (DATE_FORMAT(FROM_DAYS(TO_DAYS(now())-TO_DAYS(birthday)),'%Y')), birthday, address, referee, referee_ship, id_card_no," +
                    " fixed_telephone, is_have_children, email, zip_code,'" + treatmentUnit + "'," +
                    "   number_of_audits, auditor_time, final_auditor,0," + jfbalance + "," + moneyBalance + "," +
                    " non_transaction_level,transaction_level,characters," +
                    " consumption_habits,is_return_visit,cause_of_no_return_visit,consum_ability," +
                    " qq_number,wechat_number,other_contact,country," +
                    " province, cities,region,'" + medicalRecordNumber + "',marital_status," +
                    " occupation,'" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "', '" + DateTimeKit.now() + "'," +
                    " '" + customerPhone + "',customer_phone2,'" + fieldTc + "','" + fieldTc + "','" + doctor + "'," +
                    "remarks,'" + remarks + "','" + startTimeValue + "','" + endTimeValue + "','" + DateTimeKit.now() + "','" + yellowNumbers + "' from " + tableName
                    + " where id='" + customerId + "' ";
            sqlMapper.insert(sql);
            //根据预约ID 查询最近一次到店患者 继承转诊记录
            String sql1 = " select * from " + ShiroKit.getUser().getCustomer_info() + " t where arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null " +
                    " and reservations_id ='" + reservationsId + "' order by arrival_time desc limit 0,1 ";
            CustomerInfo info = sqlMapper.selectOne(sql1, CustomerInfo.class);
            if (info != null) {
                if (info.getReferralerPerson() == null || info.getReferralerPerson() == "" || info.getReferralerPersoned() == null || info.getReferralerPersoned() == "" || info.getReferralerTime() == null || info.getReferralerTime() == "" || info.getReferralerRemarks() == null || info.getReferralerRemarks() == "") {
                    info.setReferralerPerson("null");
                    info.setReferralerPersoned("null");
                    info.setReferralerRemarks("null");
                    info.setReferralerTime(null);
                } else {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    Date dt1 = null;
                    Date dt2 = null;
                    try {
                        dt1 = df.parse(DateTimeKit.now().substring(0, 10));
                        dt2 = df.parse(info.getReferralerTime().substring(0, 10));
                        if (dt1.getTime() - dt2.getTime() > 30 * 24 * 60 * 60 * 1000L) {
                            info.setReferralerPerson("null");
                            info.setReferralerPersoned("null");
                            info.setReferralerRemarks("null");
                            info.setReferralerTime(null);
                        } else {
                            info.setReferralerPerson(info.getReferralerPerson());
                            info.setReferralerPersoned(info.getReferralerPersoned());
                            info.setReferralerTime(info.getReferralerTime());
                            info.setReferralerRemarks(info.getReferralerRemarks());
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                String referralerPerson = "";
                String referralerPersoned = "";
                String referralerTime = "";
                String referralerRemarks = "";
                if (StringUtil.isNotEmpty(info.getReferralerPerson())) {
                    referralerPerson = "'" + info.getReferralerPerson() + "'";
                } else {
                    referralerPerson = "null";
                }
                if (StringUtil.isNotEmpty(info.getReferralerPersoned())) {
                    referralerPersoned = "'" + info.getReferralerPersoned() + "'";
                } else {
                    referralerPersoned = "null";
                }
                if (StringUtil.isNotEmpty(info.getReferralerTime())) {
                    referralerTime = "'" + info.getReferralerTime() + "'";
                } else {
                    referralerTime = null;
                }
                if (StringUtil.isNotEmpty(info.getReferralerRemarks())) {
                    referralerRemarks = "'" + info.getReferralerRemarks() + "'";
                } else {
                    referralerRemarks = "null";
                }
                String updateSql = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.referraler_person=" + referralerPerson + ",a.referraler_personed=" + referralerPersoned + "," +
                        " a.referraler_time=" + referralerTime + ",a.referraler_remarks=" + referralerRemarks + " where id='" + id + "' ";
                sqlMapper.update(updateSql);
            }
            //插入视图改动日志 复诊预约
            String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                    " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                    " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新增预约','" + ShiroKit.getUser().getId() + "','" + customerIn.getCustomerStatus() + "', '"
                    + customerIn.getCustomerName() + "', '" + customerIn.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                    "','预约项目：" + projectData + " </br>\n预约患者：" + customerIn.getCustomerName() + " </br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                    "</br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + "','" + id + "'," +
                    "'" + customerIn.getReservationsId() + "');";
            sqlMapper.insert(sq11);
            if ("1".equals(isFz)) {  //1：复诊到店，直接改为到店状态 2：复诊预约 ，点复诊状态都为复诊
                String sqlst = "select id from distinction_customer_status where " +
                        " reservations_id='" + reservationsId + "' and status=1  and left(add_time,10)<left(now(),10); ";
                List<CustomerInfo> list = sqlMapper.selectList(sqlst, CustomerInfo.class);
                String customerStatus = "";   //患者第二次到店，判断是今天到店的还是以前来过，今天到店多次客户状态都是新客首次，，点复诊状态都为复诊
                if (list.size() > 0) {
                    customerStatus = "复诊";
                } else {
                    customerStatus = "新客首次";
                }
                String sql3 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.status='到店',customer_status='" + customerStatus + "'," +
                        "arrival_time='" + DateTimeKit.now() + "'," +
                        "arrival_status=2,add_status=0 where id='" + id + "'";
                sqlMapper.update(sql3);
            }
            String sql2 = "update " + ShiroKit.getUser().getCustomer_info() + " a set a.add_status=1 where id='" + customerId + "'";
            sqlMapper.update(sql2);
            webSocket.sendMessageViews("新增预约", ShiroKit.getUser().getAbbreviation());
            membersArriveInfos = service.memberDistinguishInUp(reservationsId);
            membersArriveInfos.setIds("1");
            return membersArriveInfos;
        }
    }

    /**
     * 就诊记录 修改 保存
     */
    @RequestMapping(value = "/updateCustomerFzs", method = RequestMethod.POST)
    @ResponseBody
    public int updateCustomerFzs(String customerPhone, String projectData,
                                 String fieldTc, String doctor, String remarks, String reservationsId,
                                 String startTimeValue, String endTimeValue, String customerId) throws Exception {
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + "  set appointment_pay_service= '" + projectData + "'," +
                " field_tc='" + fieldTc + "',doctor='" + doctor + "',remarks='" + remarks + "',start_time='" + startTimeValue + "'," +
                "end_time='" + endTimeValue + "',archiving='" + ShiroKit.getUser().getAccount() + "',create_appointment_time = '" + DateTimeKit.now() + "'" +
                " where id='" + customerId + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 修改时间  通过客户ID 进行修改
     */
    @RequestMapping(value = "/updateTime", method = RequestMethod.POST)
    @ResponseBody
    public int updateGetTime(String customerId, String updateTime) {
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " t set t.arrival_time = '" + updateTime + "' where t.id = '" + customerId + "' ";
        return sqlMapper.update(sql);
    }

    /**
     * 扫码今日统计查询
     */
    @RequestMapping(value = "/scanCode", method = RequestMethod.GET)
    @ResponseBody
    public List<MembersUser> changeScanCode(String startUpdateTime1, String endUpdateTime1, String startUpdateTime2, String endUpdateTime2,
                                            String startAddTime1, String endAddTime1, String startAddTime2, String endAddTime2) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String sql = "select count(t.reservations_id) as countNum from members_user t where t.abbreviation='" + tableHead + "' and t.update_time>='" + startUpdateTime1 + "' and t.update_time<='" + endUpdateTime1 + "' " +
                "union all select count(t.reservations_id) as countNum from members_user t where t.abbreviation='" + tableHead + "' and t.update_time>='" + startUpdateTime2 + "' and t.update_time<='" + endUpdateTime2 + "'" +
                "union all select count(t.reservations_id) as countNum from members_user t where t.abbreviation='" + tableHead + "' and t.c_time>='" + startAddTime1 + "' and t.c_time<='" + endAddTime1 + "'" +
                "union all select count(t.reservations_id) as countNum from members_user t where t.abbreviation='" + tableHead + "' and t.c_time>='" + startAddTime2 + "' and t.c_time<='" + endAddTime2 + "' ;";
        List<MembersUser> infoList = sqlMapper.selectList(sql, MembersUser.class);
        return infoList;
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<ConsultantInfo> changeTotal(String startArrivalTime, String endArrivalTime, String oneChannelValue, String doctor,
                                            String twoChannelValue, String thrChannelValue, String fieldTc, String treatmentUnit,
                                            String sreach, String condition, String dealStatus, String oppStatus) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        String contitionInfo = " and t.arrival_status!=1 and t.arrival_status!=9 ";
        if (StringUtils.isNotBlank(oppStatus)) {
            if ("1".equals(oppStatus)) {
                contitionInfo += " AND tk.open_id is not null ";
            }
            if ("2".equals(oppStatus)) {
                contitionInfo += " AND tk.open_id is null ";
            }
        }
        if (!StringUtils.isNotBlank(condition)) {
            contitionInfo += " AND t.customer_status != '作废' ";
        }
        if (StringUtils.isNotBlank(startArrivalTime)) {
            contitionInfo += " and t.arrival_time >= '" + startArrivalTime + "' ";
        }
        if (StringUtils.isNotBlank(endArrivalTime)) {
            contitionInfo += " and t.arrival_time <= '" + endArrivalTime + "' ";
        }
        if (StringUtils.isNotBlank(fieldTc)) {
            contitionInfo += " and t.field_tc = '" + fieldTc + "' ";
        }
        if (StringUtils.isNotBlank(doctor)) {
            contitionInfo += " and t.doctor = '" + doctor + "' ";
        }
        if (StringUtils.isNotBlank(treatmentUnit)) {
            contitionInfo += " and t.treatment_unit ='" + treatmentUnit + "' ";
        }
        if (StringUtil.isNotEmpty(oneChannelValue)) {
            if (oneChannelValue.indexOf("请选择") == -1) {
                String oneChannel = "";
                String oneChannel2[] = oneChannelValue.split(",");
                if (oneChannel2.length == 1) {
                    oneChannel = oneChannel2[0];
                } else {
                    for (int i = 0; i < oneChannel2.length; i++) {
                        if (i == (oneChannel2.length - 1)) {
                            oneChannel += "'" + oneChannel2[i];
                        } else if (i == 0) {
                            oneChannel += oneChannel2[i] + "'" + ",";
                        } else {
                            oneChannel += "'" + oneChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.one_channel in ( '" + oneChannel + "') ";
            }
        }
        if (StringUtil.isNotEmpty(twoChannelValue)) {
            if (twoChannelValue.indexOf("请选择") == -1) {
                String twoChannel = "";
                String twoChannel2[] = twoChannelValue.split(",");
                if (twoChannel2.length == 1) {
                    twoChannel = twoChannel2[0];
                } else {
                    for (int i = 0; i < twoChannel2.length; i++) {
                        if (i == (twoChannel2.length - 1)) {
                            twoChannel += "'" + twoChannel2[i];
                        } else if (i == 0) {
                            twoChannel += twoChannel2[i] + "'" + ",";
                        } else {
                            twoChannel += "'" + twoChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.two_channel  in ('" + twoChannel + "') ";
            }
        }
        if (StringUtil.isNotEmpty(thrChannelValue)) {
            if (thrChannelValue.indexOf("请选择") == -1) {
                String thrChannel = "";
                String thrChannel2[] = thrChannelValue.split(",");
                if (thrChannel2.length == 1) {
                    thrChannel = thrChannel2[0];
                } else {
                    for (int i = 0; i < thrChannel2.length; i++) {
                        if (i == (thrChannel2.length - 1)) {
                            thrChannel += "'" + thrChannel2[i];
                        } else if (i == 0) {
                            thrChannel += thrChannel2[i] + "'" + ",";
                        } else {
                            thrChannel += "'" + thrChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.thr_channel in ('" + thrChannel + "') ";
            }
        }
        if (StringUtils.isNotBlank(dealStatus)) {
            if ("已结账".equals(dealStatus)) {
                contitionInfo += " and t.deal_status = '已结账' ";
            } else {
                contitionInfo += " and t.deal_status != '已结账' ";
            }
        }
        if (StringUtils.isNotBlank(sreach)) {
            contitionInfo += " and (t.customer_name like CONCAT('%','" + sreach + "','%') or t.customer_phone like CONCAT('%','" + sreach + "','%') or " +
                    " t.wechat_number like CONCAT('%','" + sreach + "','%') or t.medical_record_number like CONCAT('%','" + sreach + "','%') or t.szm like CONCAT('%" + sreach + "%')) ";
        }
        String sql = "select count(distinct t.reservations_id) as countNum,sum(actual_account_balance) as actualAccountBalanceNum from " + tableName + " t  left join members_user tk on t.reservations_id = tk.reservations_id where 1=1 " + contitionInfo +

                " union all select count(distinct t.reservations_id) as countNum,sum(actual_account_balance) as actualAccountBalanceNum  from " + tableName + " t left join members_user tk on t.reservations_id = tk.reservations_id  where t.customer_status='新客首次' " + contitionInfo +

                " union all select count(distinct t.reservations_id) as countNum ,sum(actual_account_balance) as actualAccountBalanceNum from " + tableName + " t left join members_user tk on t.reservations_id = tk.reservations_id  where t.customer_status='新客多次' " + contitionInfo +

                " union all select count(distinct t.reservations_id) as countNum,sum(actual_account_balance) as actualAccountBalanceNum  from " + tableName + " t left join members_user tk on t.reservations_id = tk.reservations_id  where t.customer_status='复诊' " + contitionInfo +

                " union all select count(distinct t.reservations_id) as countNum ,sum(actual_account_balance) as actualAccountBalanceNum from " + tableName + " t left join members_user tk on t.reservations_id = tk.reservations_id  where t.customer_status='老客'" + contitionInfo +

                //复诊人次
                " union all select count(tt.countNum) as countNum ,count(tt.actualAccountBalanceNum) as actualAccountBalanceNum from " +
                "(select count(distinct t.reservations_id) as countNum ,sum(actual_account_balance) as actualAccountBalanceNum " +
                " from " + tableName + " t left join members_user tk on t.reservations_id = tk.reservations_id where t.customer_status in ('复诊')  " + contitionInfo + "  group by t.reservations_id, left(arrival_time,10) ) tt";

        List<ConsultantInfo> infoList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return infoList;
    }

    /**
     * 临时患者新加一条用户数据
     */
    @RequestMapping(value = "/temporaryCustomer", method = RequestMethod.POST)
    @ResponseBody
    public String temporaryCustomer(String customerName, String customerAge, String customerPhone, String customerSex, String phoneSharShip) throws Exception {
        ReservationsInfo reservationsInfo = reservationsService.getCustomerPhoneCount(customerPhone);
        if (reservationsInfo != null) {
            return "0,";
        } else {
            String ageRange = "";
            if (!("").equals(customerAge)) {
                for (int i = 0; i < 11; i++) {
                    if (Integer.parseInt(customerAge) >= (i * 10) && Integer.parseInt(customerAge) <= (i * 10 + 9)) {
                        if (i < 10) {
                            ageRange = (i * 10) + "-" + (i * 10 + 9);
                        } else {
                            ageRange = "99+";
                        }
                    }
                }
                if (Integer.parseInt(customerAge) >= 100) {
                    ageRange = "99+";
                }
            } else {
                ageRange = "99+";
                customerAge = null;
            }
            if (phoneSharShip == null || phoneSharShip == "") {
                phoneSharShip = "本人";
            }
            CustomerInfo info = new CustomerInfo();
            info.setCustomerAge(Integer.parseInt(customerAge));
            info.setCustomerSex(Integer.parseInt(customerSex));
            if (!"本人".equals(phoneSharShip)) {
                String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone='" + customerPhone + "' or customer_phone2='" + customerPhone + "'";
                List<CustomerInfo> infoList = sqlMapper.selectList(sql1, CustomerInfo.class);
                if (infoList.size() > 0) {
                    int count = infoList.size();
                    customerPhone = customerPhone + "+" + count;
                    String id = service.getId();
                    String sql = "insert into " + ShiroKit.getUser().getCustomer_info() + " (id,customer_name,customer_age,age_range,customer_phone,customer_sex," +
                            "status,update_time,filing_time,arrival_status,diagnosis_status,deal_status,isdeal_status,szm,phone_shar_ship,customer_sex_head) " +
                            "values('" + id + "','" + customerName + "'," + customerAge + ",'" + ageRange + "','" + customerPhone + "','" + customerSex + "'," +
                            "'预约','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','9','未看诊','未开单','未成交',firstconcats('" + customerName + "'),'" + phoneSharShip + "'," +
                            "'" + customerPublicService.getSexPt(info) + "')";
                    return sqlMapper.insert(sql) + "," + id;
                } else {
                    String id = service.getId();
                    String sql = "insert into " + ShiroKit.getUser().getCustomer_info() + " (id,customer_name,customer_age,age_range,customer_phone,customer_sex," +
                            "status,update_time,filing_time,arrival_status,diagnosis_status,deal_status,isdeal_status,szm,phone_shar_ship,customer_sex_head) " +
                            "values('" + id + "','" + customerName + "'," + customerAge + ",'" + ageRange + "','" + customerPhone + "','" + customerSex + "'," +
                            "'预约','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','9','未看诊','未开单','未成交',firstconcats('" + customerName + "'),'" + phoneSharShip + "'," +
                            "'" + customerPublicService.getSexPt(info) + "')";
                    return sqlMapper.insert(sql) + "," + id;
                }
            } else {
                String sql1 = "select * from " + ShiroKit.getUser().getCustomer_info() + " where customer_phone='" + customerPhone + "' or customer_phone2='" + customerPhone + "'";
                List<CustomerInfo> infoList = sqlMapper.selectList(sql1, CustomerInfo.class);
                if (infoList.size() > 0) {
                    return "0,";
                } else {
                    String id = service.getId();
                    String sql = "insert into " + ShiroKit.getUser().getCustomer_info() + " (id,customer_name,customer_age,age_range,customer_phone,customer_sex," +
                            "status,update_time,filing_time,arrival_status,diagnosis_status,deal_status,isdeal_status,szm,phone_shar_ship,one_channel,one_medium,customer_sex_head) " +
                            "values('" + id + "','" + customerName + "'," + customerAge + ",'" + ageRange + "','" + customerPhone + "','" + customerSex + "'," +
                            "'预约','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','9','未看诊','未开单','未成交',firstconcats('" + customerName + "')," +
                            "'" + phoneSharShip + "','直接上门','直接上门'," +
                            "'" + customerPublicService.getSexPt(info) + "')";
                    return sqlMapper.insert(sql) + "," + id;
                }
            }
        }
    }

    /**
     * 初诊预约新加一条用户数据
     */
    @RequestMapping(value = "/addTemporaryCustomer", method = RequestMethod.POST)
    @ResponseBody
    public int addTemporaryCustomer(String customerPhone, String projectData, String duration, String treatmentUnit,
                                    String fieldTc, String doctor, String remarks, String reservationsId,
                                    String startTimeValue, String customerId) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = formatter.parse(startTimeValue);
        Date date1 = new Date(date.getTime() + Integer.parseInt(duration) * 60 * 1000);
        String endTimeValue = formatter.format(date1);
        Random rand = new Random();
        int randomNumber = rand.nextInt(9999);
        String selsql = "select id,a.arrival_status,(case a.arrival_status when (1 or 9) then '预约' when 2 then '到店' when 3 then '就诊中'  " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话'  " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName,a.customer_name,a.customer_phone,a.customer_status," +
                "a.reservations_id from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "'";
        CustomerInfo cinfo = sqlMapper.selectOne(selsql, CustomerInfo.class);
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set appointment_pay_service='" + projectData + "',update_time='" + DateTimeKit.now() + "'," +
                " update_people='" + ShiroKit.getUser().getAccount() + "',archiving='" + ShiroKit.getUser().getAccount() + "'," +
                " field_tc='" + fieldTc + "',query_tc='" + fieldTc + "',doctor='" + doctor + "',remarks_reservation='" + remarks + "',start_time='" + startTimeValue + "'," +
                " end_time='" + endTimeValue + "',create_appointment_time='" + DateTimeKit.now() + "'," +
                " treatment_unit='" + treatmentUnit + "',medical_record_number='LS" + randomNumber + "' " +
                " where id='" + customerId + "'";
        //插入视图改动日志 新诊预约
        String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新增预约','" + ShiroKit.getUser().getId() + "','" + cinfo.getCustomerStatus() + "', '"
                + cinfo.getCustomerName() + "', '" + cinfo.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','预约项目：" + projectData + " </br>\n预约患者：" + cinfo.getCustomerName() + "</br>\n预约时间：" + startTimeValue.substring(0, 16) + " - " + endTimeValue.substring(11, 16) + " " +
                "</br>\n预约状态：预约 </br>\n预约科室：" + treatmentUnit + " </br>\n预约医生：" + doctor + " </br>\n咨询师：" + fieldTc + " </br>\n备注：" + remarks + " '," +
                "'" + customerId + "','" + cinfo.getReservationsId() + "');";
        sqlMapper.insert(sq11);
        webSocket.sendMessageViews("新增预约", ShiroKit.getUser().getAbbreviation());
        return sqlMapper.update(sql);
    }

    /**
     * 新诊预约点挂号信息回显
     */
    @RequestMapping(value = "/getTemporaryCustomer/{customerId}")
    public String getTemporaryCustomer(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String selsql = "select a.arrival_status,(case a.arrival_status when (1 or 9 or 6 or 10) then '预约' when 2 then '到店' when 3 then '就诊中' " +
                "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话' " +
                "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName," +
                "a.* from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selsql, CustomerInfo.class);
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getCharactersList() == null) {
            String getListSql = "select id, characters from character_info order by num asc;";
            List<CharacterInfo> charactersList=sqlMapper.selectList(getListSql,CharacterInfo.class);
            ShiroKit.getUser().setCharactersList(charactersList);
        }
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("consumAbilityList") == null) {
            String getListSql = "select id, consum_ability from consum_ability_info order by  num asc;";
            List<ConsumAbilityInfo> consumAbilityList = sqlMapper.selectList(getListSql, ConsumAbilityInfo.class);
            ShiroKit.setSessionAttr("consumAbilityList", consumAbilityList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
        if (ShiroKit.getUser().getConsumptionHabitsList() == null) {
            String getListSql = "select id, consumption_habits from consumption_habits_info order by  num asc;";
            List<ConsumptionHabitsInfo> consumptionHabitsList = sqlMapper.selectList(getListSql, ConsumptionHabitsInfo.class);
            ShiroKit.getUser().setConsumptionHabitsList(consumptionHabitsList);
        }
        if (customerInfo.getReservationsId() == null || customerInfo.getReservationsId() == "null" || customerInfo.getReservationsId() == "") {
            String selsql1 = "select * from reservations_info a where customer_phone = '" + customerInfo.getCustomerPhone() + "' and id is not null limit 1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(selsql1, ReservationsInfo.class);
            if (reservationsInfo != null) {//跟进人，为空，建档人给归属人
                if (StringUtil.isEmpty(reservationsInfo.getFollower())) {
                    String sql1 = "update reservations_info set belonger='" + reservationsInfo.getArchiving() + "' where id = '" + reservationsInfo.getId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set belonger='" + reservationsInfo.getArchiving() + "' where id = '" + reservationsInfo.getId() + "'";
                    sqlMapper.update(sqlsc);
                    customerInfo.setScarchiving(reservationsInfo.getArchiving());
                } else {   //跟进人，不为空或待定，跟进人给归属人
                    String sql1 = "update reservations_info set belonger='" + reservationsInfo.getFollower() + "' where id = '" + reservationsInfo.getId() + "'";
                    sqlMapper.update(sql1);
                    String sqlsc = "update reservations_infosc set belonger='" + reservationsInfo.getFollower() + "' where id = '" + reservationsInfo.getId() + "'";
                    sqlMapper.update(sqlsc);
                    customerInfo.setScarchiving(reservationsInfo.getFollower());
                }
                String updasql = "update " + ShiroKit.getUser().getCustomer_info() + " a set scarchiving='" + customerInfo.getScarchiving() + "'" +
                        ",one_channel='" + reservationsInfo.getOneChannel() + "',two_channel='" + reservationsInfo.getTwoChannel() + "',thr_channel='" + reservationsInfo.getThrChannel() + "'" +
                        ",one_medium='" + reservationsInfo.getOneMedium() + "',two_medium='" + reservationsInfo.getTwoMedium() + "',thr_medium='" + reservationsInfo.getThrMedium() + "'" +
                        ",reservations_id='" + reservationsInfo.getId() + "',first_visit_date='" + DateTimeKit.now() + "',customer_phone2='" + reservationsInfo.getCustomerPhone2() + "'" +
                        " where customer_phone = '" + customerInfo.getCustomerPhone() + "'";
                sqlMapper.update(updasql);
                String selsql2 = "select a.arrival_status,(case a.arrival_status when (1 or 9 or 6 or 10) then '预约' when 2 then '到店' when 3 then '就诊中' " +
                        "when 4 then '完成治疗' when 5 then '离开' when (6 or 10) then '已打电话' " +
                        "when 7 then '失约' when 8 then '取消预约' else '其他' end) as arrivalStatusName," +
                        "a.* from  " + ShiroKit.getUser().getCustomer_info() + " a where id = '" + customerId + "'";
                CustomerInfo customerInfo2 = sqlMapper.selectOne(selsql2, CustomerInfo.class);
                model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
                model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
                model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
                model.addAttribute("tcList", ShiroKit.getUser().getTcList());
                model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
                model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
                model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
                model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
                model.addAttribute("customerInfo", customerInfo2);
                return PREFIX + "customer_receptionSix.html";
            }
        }
        model.addAttribute("consumptionHabitsList", ShiroKit.getUser().getConsumptionHabitsList());
        model.addAttribute("refereeShipList", ShiroKit.getUser().getRefereeShipInfoList());
        model.addAttribute("consumAbilityList", ShiroKit.getSessionAttr("consumAbilityList"));
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("occupationList", ShiroKit.getUser().getOccupationInfoList());
        model.addAttribute("economicAbilityList", ShiroKit.getUser().getEconomicAbilityList());
        model.addAttribute("charactersList", ShiroKit.getUser().getCharactersList());
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "customer_receptionFive.html";
    }

    /**
     * 新诊预约点挂号
     */
    @RequestMapping(value = "/addTemporaryCustomerOK", method = RequestMethod.POST)
    @ResponseBody
    public int addTemporaryCustomerOK(@Valid CustomerInfo info, BindingResult result, Model model) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String id = "";
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        if (info.getReferee() != null && info.getReferee() != "") {
            id = "ldx" + CommUtils.getUUID() + randomNumber;
//            info.setOneChannel(info.getOneMedium());
//            info.setTwoChannel(info.getTwoMedium());
//            info.setThrChannel(info.getThrMedium());
        } else {
            id = "zd" + CommUtils.getUUID() + randomNumber;
        }
        String customerid = service.getId();
        info.setCustomerId(customerid);
        info.setMedicalRecordNumber(service.getMedicalRecordNumbers(info.getCustomerPhone(), ShiroKit.getUser().getMedicalrecord_info()));
        String phoneSql3 = "select id,filing_time from reservations_info a " +
                " where (customer_phone like '%" + info.getCustomerPhone() + "%' or customer_phone2 like '%" + info.getCustomerPhone() + "%' )";
        List<ReservationsInfo> reservationsInfoList = sqlMapper.selectList(phoneSql3, ReservationsInfo.class);
        if (reservationsInfoList.size() == 0) {   //不是市场人员新建的洁牙预约 ，插入数据到总表
            info.setReservationsId(id);
            reservationsService.insert(info);
        } else {   //是市场人员新建的洁牙预约 ，不插入总表，修改为到店
            String upda = "update reservations_infosc set customer_sex='" + info.getCustomerSex() + "'," +
                    " customer_age=" + info.getCustomerAge() + ",province='" + info.getProvince() + "',cities='" + info.getCities() + "'," +
                    " region='" + info.getRegion() + "',address='" + info.getAddress() + "',occupation='" + info.getOccupation() + "'," +
                    " identification_number='" + info.getMedicalRecordNumber() + "',status='到店'," +
                    " first_visit_date='" + DateTimeKit.now() + "',arrival_store='" + ShiroKit.getUser().getOutpatientName() + "' " +
                    " where id='" + reservationsInfoList.get(0).getId() + "'";
            sqlMapper.update(upda);
            info.setReservationsId(reservationsInfoList.get(0).getId());
            info.setMarketFilingTime(reservationsInfoList.get(0).getFilingTime());
        }
        reservationsService.insertCustomerStatus(info);   //加入客户状态表
        service.insertxz(info);   //门诊预约初诊到店挂号
        //插入视图改动日志 新诊挂号
        String sq11 = "INSERT INTO `customer_reservations_update_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','新诊预约点挂号','" + ShiroKit.getUser().getId() + "','" + info.getCustomerStatus() + "', '"
                + info.getCustomerName() + "', '" + info.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','预约状态：预约->挂号','" + info.getCustomerId() + "','" + info.getReservationsId() + "');";
        //插入号修改日志
        String sq12 = "INSERT INTO `customer_medical_number_log` (createtime,single_person,logtype, `userid`, `customer_status`, `customer_name`,`customer_phone`," +
                " `succeed`,outpatient_name ,`message`,customer_id,reservations_id) VALUES " +
                " ('" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','挂号生成','" + ShiroKit.getUser().getId() + "','" + info.getCustomerStatus() + "', '"
                + info.getCustomerName() + "', '" + info.getCustomerPhone() + "','成功','" + ShiroKit.getUser().getOutpatientName() +
                "','生成的病历号为:" + info.getMedicalRecordNumber() + " ','" + info.getCustomerId() + "','" + info.getReservationsId() + "');";
        String upcussql1 = "update " + ShiroKit.getUser().getCustomer_info() + " set arrival_status=1 where arrival_status=9 and reservations_id='" + info.getReservationsId() + "';";
        String upcussql2 = "update " + ShiroKit.getUser().getCustomer_info() + " set arrival_status=6 where arrival_status=10 and reservations_id='" + info.getReservationsId() + "';";
        sqlMapper.update(upcussql1);
        sqlMapper.update(upcussql2);
        sqlMapper.insert(sq12);
        webSocket.sendMessageViews("新诊预约点挂号", ShiroKit.getUser().getAbbreviation());
        return sqlMapper.insert(sq11);
    }

    @RequestMapping(value = "/customerExport")
    public void reservationsExport(@Valid SearchCustomerInfo searchInfo, HttpServletResponse response) {
        try {
            List<CustomerInfo> list = service.customerExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 27; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("病历号");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("电话");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("电话2");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("使用人");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("科室");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("二级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("三级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("客户状态");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("开单状态");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("扫码状态");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("已交金额");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("欠费");
            cell.setCellStyle(style);
            cell = row.createCell(16);
            cell.setCellValue("现场TC");
            cell.setCellStyle(style);
            cell = row.createCell(17);
            cell.setCellValue("医生");
            cell.setCellStyle(style);
            cell = row.createCell(18);
            cell.setCellValue("到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(19);
            cell.setCellValue("初诊时间");
            cell.setCellStyle(style);
            cell = row.createCell(20);
            cell.setCellValue("黄页编号");
            cell.setCellStyle(style);
            cell = row.createCell(21);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            cell = row.createCell(22);
            cell.setCellValue("网电咨询师");
            cell.setCellStyle(style);
            cell = row.createCell(23);
            cell.setCellValue("一级媒介");
            cell.setCellStyle(style);
            cell = row.createCell(24);
            cell.setCellValue("二级媒介");
            cell.setCellStyle(style);
            cell = row.createCell(25);
            cell.setCellValue("三级媒介");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                CustomerInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 27; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(map.getMedicalRecordNumber());
                row.getCell(1).setCellValue(map.getCustomerName());
                if (ShiroKit.getUser().getPhonePrivilegesexp() == 1) {
                    String customerPhone="";
                    String customerPhone2="";
                    if(!StringUtil.isEmpty(map.getCustomerPhone())){
                        customerPhone=map.getCustomerPhone();
                    }
                    if(!StringUtil.isEmpty(map.getCustomerPhone2())){
                        customerPhone2=map.getCustomerPhone2();
                    }
                    row.getCell(2).setCellValue(customerPhone);
                    row.getCell(3).setCellValue(customerPhone2);
                } else {
                    row.getCell(2).setCellValue("无");
                    row.getCell(3).setCellValue("无");
                }
                row.getCell(4).setCellValue(map.getPhoneSharShip());
                String customerSex="";
                int customerAge=0;
                if(!StringUtil.isEmpty(map.getSex())){
                    customerSex=map.getSex();
                }
                if(!StringUtil.isEmpty(map.getCustomerAge())){
                    customerAge=map.getCustomerAge();
                }
                row.getCell(5).setCellValue(customerSex);
                row.getCell(6).setCellValue(customerAge);
                row.getCell(7).setCellValue(map.getTreatmentUnit());
                row.getCell(8).setCellValue(map.getOneChannel());
                row.getCell(9).setCellValue(map.getTwoChannel());
                row.getCell(10).setCellValue(map.getThrChannel());
                row.getCell(11).setCellValue(map.getCustomerStatus());
                row.getCell(12).setCellValue(map.getDealStatus());
                if (StringUtil.isEmpty(map.getOppStatus())) {
                    row.getCell(13).setCellValue("未扫码");
                } else {
                    row.getCell(13).setCellValue("已扫码");
                }
                row.getCell(14).setCellValue(map.getActualAccountBalance() + map.getMoneyBalance());
                row.getCell(15).setCellValue(map.getAccountArrears());
                row.getCell(16).setCellValue(map.getFieldTc());
                row.getCell(17).setCellValue(map.getDoctor());
                row.getCell(18).setCellValue(map.getArrivalTime());
                row.getCell(19).setCellValue(map.getFirstVisitDate());
                row.getCell(20).setCellValue(map.getYellowNumber());
                row.getCell(21).setCellValue(map.getRemarks());
                row.getCell(22).setCellValue(map.getScarchiving());
                row.getCell(23).setCellValue(map.getOneMedium());
                row.getCell(24).setCellValue(map.getTwoMedium());
                row.getCell(25).setCellValue(map.getThrMedium());
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}